@wcstack/state 1.31.0 → 1.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/auto.min.js CHANGED
@@ -1,2 +1,2 @@
1
- function t(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const e={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},n=".",o="*",s=128,r="|",i="prevent",a="stop",l="ro",c="init",d="sync",u="else",f="...",h="on",p="eventToken",m="command",g="class",y="attr",b="style",w={};for(let t=0;t<128;t++)w[`$${t+1}`]=t;const v=Object.freeze(w),N="$connectedCallback",S="$disconnectedCallback",I="$updatedCallback",x="$stateReadyCallback",$="$bindables",P="$commands",_="$commandTokens",A="$command",k="$eventTokens",C="$on",E="$streams",M="$watch",T="$listKeys",O="$streamStatus",R="$streamError",D="data-wc-definition",L=new WeakMap,j=new WeakSet;let W=0;async function B(t){const e=function(t){let e,n=L.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++W,promise:o,resolve:e},L.set(t,n),j.has(t)&&n.resolve(),n}(t);await e.promise}function F(t){const e=L.get(t);void 0===e?j.add(t):e.resolve()}const z=new Map;let q=0;function U(t){let e=z.get(t);return void 0!==e||(e=Object.freeze(new H(t)),z.set(t,e)),e}class H{id=++q;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:U(e),n=t.split("."),s=[],r=[],i=[],a={},l=[],c=[],d=[],u=[];let f="",h="",p=0;for(let t=0;t<n.length;t++)f+=n[t],n[t]===o&&(i.push(f),a[f]=p,l.push(e(f)),c.push(h),d.push(e(h)),u.push(t),p++),s.push(f),r.push(e(f)),h=f,f+=".";const m=i.length>0?i[i.length-1]:null,g=s.length>1?s[s.length-2]:null;this.path=t,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=s,this.cumulativePathSet=new Set(s),this.cumulativePathInfos=r,this.cumulativePathInfoSet=new Set(r),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 V=new WeakMap;function G(t){const e=V.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{V.set(t,n)}}function K(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function J(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return K(e);if(void 0!==n)return K(n)}return K(globalThis.customElements)}function X(t,e){t.upgrade?.(e)}function Y(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=et(s.properties,Q);if(null===r)return null;const i=void 0===s.inputs?new Map:et(s.inputs,Z);if(null===i)return null;const a=void 0===s.commands?new Map:et(s.commands,tt);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Q(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 Z(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 tt(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 et(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 nt(t){throw new Error(`[@wcstack/state] ${t}`)}function ot(t,e,n){const o="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:o,statePathInfo:U(o),stateName:n,inFilters:[],outFilters:[],bindingType:"prop"}}function st(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function rt(t,e,n={}){const o=n.allowDeferred??!0;if(!e.some(t=>"spread"===t.bindingType))return e;const s=[],r=new WeakSet;for(const n of e){if("spread"!==n.bindingType){s.push(n);continue}t.nodeType!==Node.ELEMENT_NODE&&nt("Spread binding requires an element node.");const e=t,i=G(e);null===i&&nt(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=J(e);null===a&&nt(`CustomElementRegistry is unavailable for <${i}>.`);if(void 0===a.get(i)){o||nt(`Spread binding "${n.statePathName}" requires <${i}> to be registered. Define the custom element before initializing this binding.`),s.push(n);continue}X(a,e);const l=Y(e);null===l&&nt(`Spread binding "${n.statePathName}" requires <${i}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=n.stateName,u=new Set;for(const t of l.knownProperties.keys()){if(u.has(t))continue;u.add(t);const e=ot(t,c,d);r.add(e),s.push(e)}for(const t of l.declaredInputs.keys()){if(u.has(t))continue;u.add(t);const e=ot(t,c,d);r.add(e),s.push(e)}}const i=new Map;for(let t=0;t<s.length;t++){const e=st(s[t]);null!==e&&i.set(e,t)}const a=[];for(let t=0;t<s.length;t++){const e=st(s[t]);null!==e?i.get(e)===t&&a.push(s[t]):a.push(s[t])}return a}function it(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 at=new WeakMap;function lt(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 ct(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=lt(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const dt=" Validate statically: npx @wcstack/lint <file>.",ut=new Set(["if","elseif","else","for"]);function ft(t){nt(`filter ${t} requires at least one option`)}function ht(t){nt(`filter ${t} requires a number as option`)}function pt(t){nt(`filter ${t} requires a number value`)}function mt(t){nt(`filter ${t} requires a date value`)}function gt(t){return!(!t||isNaN(Number(t)))}const yt={eq:t=>{const e=t?.[0]??ft("eq");return t=>"number"==typeof t?(gt(e)||ht("eq"),t===Number(e)):t===e},ne:t=>{const e=t?.[0]??ft("ne");return t=>"number"==typeof t?(gt(e)||ht("ne"),t!==Number(e)):t!==e},not:t=>t=>("boolean"!=typeof t&&nt(`filter ${"not"} requires a boolean value`),!t),lt:t=>{const e=t?.[0]??ft("lt");return gt(e)||ht("lt"),t=>("number"!=typeof t&&pt("lt"),t<Number(e))},le:t=>{const e=t?.[0]??ft("le");return gt(e)||ht("le"),t=>("number"!=typeof t&&pt("le"),t<=Number(e))},gt:t=>{const e=t?.[0]??ft("gt");return gt(e)||ht("gt"),t=>("number"!=typeof t&&pt("gt"),t>Number(e))},ge:t=>{const e=t?.[0]??ft("ge");return gt(e)||ht("ge"),t=>("number"!=typeof t&&pt("ge"),t>=Number(e))},inc:t=>{const e=t?.[0]??ft("inc");return gt(e)||ht("inc"),t=>("number"!=typeof t&&pt("inc"),t+Number(e))},dec:t=>{const e=t?.[0]??ft("dec");return gt(e)||ht("dec"),t=>("number"!=typeof t&&pt("dec"),t-Number(e))},mul:t=>{const e=t?.[0]??ft("mul");return gt(e)||ht("mul"),t=>("number"!=typeof t&&pt("mul"),t*Number(e))},div:t=>{const e=t?.[0]??ft("div");return gt(e)||ht("div"),t=>("number"!=typeof t&&pt("div"),t/Number(e))},mod:t=>{const e=t?.[0]??ft("mod");return gt(e)||ht("mod"),t=>("number"!=typeof t&&pt("mod"),t%Number(e))},abs:t=>t=>("number"!=typeof t&&pt("abs"),Math.abs(t)),clamp:t=>{const e=t?.[0]??ft("clamp");gt(e)||ht("clamp");const n=t?.[1]??ft("clamp");gt(n)||ht("clamp");const o=Number(e),s=Number(n);return t=>("number"!=typeof t&&pt("clamp"),Math.min(Math.max(t,o),s))},fix:t=>{const e=t?.[0]??"0";return gt(e)||ht("fix"),t=>("number"!=typeof t&&pt("fix"),t.toFixed(Number(e)))},locale:t=>{const n=t?.[0]??e.locale;return t=>("number"!=typeof t&&pt("locale"),t.toLocaleString(n))},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]??ft("slice");gt(n)||ht("slice"),e.push(Number(n));const o=t?.[1];return void 0!==o&&(gt(o)||ht("slice"),e.push(Number(o))),t=>String(t).slice(...e)},substr:t=>{const e=t?.[0]??ft("substr");gt(e)||ht("substr");const n=t?.[1]??ft("substr");return gt(n)||ht("substr"),t=>String(t).substr(Number(e),Number(n))},pad:t=>{const e=t?.[0]??ft("pad");gt(e)||ht("pad");const n=t?.[1]??"0";return t=>String(t).padStart(Number(e),n)},rep:t=>{const e=t?.[0]??ft("rep");return gt(e)||ht("rep"),t=>String(t).repeat(Number(e))},rev:t=>t=>String(t).split("").reverse().join(""),truncate:t=>{const e=t?.[0]??ft("truncate");gt(e)||ht("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)||nt(`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 gt(e)||ht("round"),t=>{"number"!=typeof t&&pt("round");const n=Math.pow(10,Number(e));return Math.round(t*n)/n}},floor:t=>{const e=t?.[0]??"0";return gt(e)||ht("floor"),t=>{"number"!=typeof t&&pt("floor");const n=Math.pow(10,Number(e));return Math.floor(t*n)/n}},ceil:t=>{const e=t?.[0]??"0";return gt(e)||ht("ceil"),t=>{"number"!=typeof t&&pt("ceil");const n=Math.pow(10,Number(e));return Math.ceil(t*n)/n}},percent:t=>{const e=t?.[0]??"0";return gt(e)||ht("percent"),t=>("number"!=typeof t&&pt("percent"),`${(100*t).toFixed(Number(e))}%`)},unit:t=>{const e=t?.[0]??ft("unit");return t=>null==t?t:String(t)+e},date:t=>{const n=t?.[0]??e.locale;return t=>(t instanceof Date||mt("date"),t.toLocaleDateString(n))},time:t=>{const n=t?.[0]??e.locale;return t=>(t instanceof Date||mt("time"),t.toLocaleTimeString(n))},datetime:t=>{const n=t?.[0]??e.locale;return t=>(t instanceof Date||mt("datetime"),t.toLocaleString(n))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||mt("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||mt("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]??ft("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},bt=yt,wt={input:yt,output:bt},vt=(t,e)=>n=>{const o=n[t];return o||nt(`[wcs/filter-unknown] filter not found: ${t}.${ct(t,Object.keys(n))}${dt}`),o(e)};function Nt(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 St=new Map;function It(t,e){const n=wt[e];return t.map(t=>{const o=t.indexOf("("),s=t.lastIndexOf(")");if(-1!==o&&-1===s&&nt(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==s&&-1===o&&nt(`Invalid filter format: missing opening parenthesis in "${t}"`),-1===o){const o=t.trim(),s=`${o}():${e}`;let r=St.get(s);return void 0===r&&(r=vt(o,[])(n),St.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(Nt(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=Nt(n,r,i);return(l||s)&&e.push(l),e}(r),l=`${i}(${a.join(",")}):${e}`;let c=St.get(l);return void 0===c&&(c=vt(i,a)(n),St.set(l,c)),{filterName:i,args:a,filterFn:c}}})}const xt=t=>t.trim(),$t=new Map;const Pt=new Map;function _t(t){const e=t.indexOf(r);let n="",o=[],s="",i=[];-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),Pt.has(s)?i=Pt.get(s):(o=s.split(r).map(xt),i=It(o,"output"),Pt.set(s,i))):n=t.trim();const[a,l="default"]=n.split("@").map(xt);return{stateName:l,statePathName:a,statePathInfo:U(a),outFilters:i}}function At(t){const[...e]=t.split(";").map(xt).filter(t=>t.length>0),o=e.map(t=>{const e=t.indexOf(":");-1===e&&nt(`Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.`);const o=t.slice(0,e).trim(),s=t.slice(e+1).trim();if(o===u){const t=U("#else");return{propName:u,propSegments:[u],propModifiers:[],statePathName:"#else",statePathInfo:t,stateName:"",inFilters:[],outFilters:[],bindingType:"else"}}if(o===f){const e=_t(s);return e.outFilters.length>0&&nt(`Invalid spread binding "${t}": filters are not allowed on spread targets.`),0===e.statePathName.length&&nt(`Invalid spread binding "${t}": spread target path is required.`),{propName:f,propSegments:[f],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===o||"elseif"===o||"for"===o||"radio"===o||"checkbox"===o){return{propName:o,propSegments:[o],propModifiers:[],inFilters:[],..._t(s),bindingType:o}}{const t=_t(s),e=function(t){const e=t.indexOf(r);let o="",s=[],i="",a=[];-1!==e?(o=t.slice(0,e).trim(),i=t.slice(e+1).trim(),$t.has(i)?a=$t.get(i):(s=i.split(r).map(xt),a=It(s,"input"),$t.set(i,a))):o=t.trim();const[l,c]=o.split("#").map(xt),d=l.split(n).map(xt);return{propName:l,propSegments:d,propModifiers:c?c.split(",").map(xt):[],inFilters:a}}(o);return e.propSegments[0]===p||e.propSegments[0].startsWith(h)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});if(o.length>1){o.some(t=>ut.has(t.bindingType))&&nt(`[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">).${dt}`)}return o}const kt=new WeakMap,Ct=new Set([e.commentTextPrefix,e.commentForPrefix,e.commentIfPrefix,e.commentElseIfPrefix,e.commentElsePrefix]),Et=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Mt(t){const n=kt.get(t);if("string"==typeof n)return n;if(t.nodeType!==Node.COMMENT_NODE)return null;const o=t.data.trim(),s=Et.exec(o);if(null===s)return null;const r=s[1]||e.commentTextPrefix;return Ct.has(r)?(kt.set(t,s[2]),s[2]):null}function Tt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],..._t(t),bindingType:"text"}}const Ot=new Map;function Rt(t,e,n){if(null===n)Ot.delete(t);else{Ot.set(t,n);const o=n.parseBindTextResult,s=ti(e,o.stateName);null===s&&nt(`State element with name "${o.stateName}" not found for fragment info.`),s.setPathInfo(o.statePathName,o.bindingType);for(const t of n.nodeInfos)for(const n of t.parseBindTextResults){const t=ti(e,n.stateName);null===t&&nt(`State element with name "${n.stateName}" not found for fragment info node.`),t.setPathInfo(n.statePathName,n.bindingType)}}}function Dt(t){return Ot.get(t)||null}function Lt(t){if(t.nodeType===Node.ELEMENT_NODE){return At(t.getAttribute(e.bindAttributeName)||"")}if(t.nodeType===Node.COMMENT_NODE){const e=Mt(t);null===e&&nt("Comment node binding text not found.");const n=Dt(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Tt(e),s=null):s=e,[{...o,uuid:s}]}return[]}function jt(t){if(!t.hasAttribute("bind-component"))return!1;const n=t.parentNode;return n instanceof Element&&n.hasAttribute(e.bindAttributeName)}function Wt(t){const n=[],o=t.querySelectorAll(`${e.tagNames.state}[bind-component]`);for(const e of o){if(!jt(e))continue;const o=e.parentNode;o!==t&&n.push(o)}return n}function Bt(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 Ft(t){const n=[],o=Wt(t),s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(t){if(t.nodeType===Node.ELEMENT_NODE){return t.hasAttribute(e.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==Mt(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const t=s.currentNode;o.length>0&&Bt(t,o)||n.push(t)}return n}const zt=new WeakSet;function qt(t,e,n){const o=rt(t,e,{allowDeferred:n.allowDeferred});if(o.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?G(t):null;return null===n&&nt("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e}}}zt.add(t);const s=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,o);return function(t,e){at.set(t,e)}(t,s),F(t),{bindings:s,deferred:null}}function Ut(t){const e=Ft(t),n=[],o=[];for(const t of e){if(zt.has(t))continue;const e=qt(t,Lt(t),{allowDeferred:!0});null===e.deferred?n.push(...e.bindings):o.push(e.deferred)}return[e,n,o]}function Ht(t){zt.add(t)}function Vt(t){const{node:e,parseResults:n}=t;!function(t){zt.delete(t)}(e);return qt(e,n,{allowDeferred:!1}).bindings}const Gt=new WeakMap;function Kt(t){let e=t;for(;e;){const t=Gt.get(e);if(t)return t;e=e.parentNode}return null}function Jt(t,e){null!==e?Gt.set(t,e):Gt.delete(t)}let Xt=null;const Yt=new WeakMap;function Qt(t){return Yt.get(t)??[]}function Zt(t,e){Yt.set(t,e)}const te=Symbol("$$setLoopContext"),ee=Symbol("$$getByAddress"),ne=Symbol("$$hasByAddress"),oe=Symbol("$$setByAddress"),se=Symbol("$$connectedCallback"),re=Symbol("$$disconnectedCallback"),ie=Symbol("$$updatedCallback"),ae=new WeakMap;function le(t,e){if(ae.has(t)){const n=ae.get(t);if(n.has(e))return n.get(e)}else ae.set(t,new WeakMap);const n=Object.freeze(new ce(t,e));return ae.get(t).set(e,n),n}class ce{pathInfo;stateName;stateElement;parentAbsolutePathInfo;constructor(t,e){this.pathInfo=e,this.stateName=t.name,this.stateElement=t,null===e.parentPathInfo?this.parentAbsolutePathInfo=null:this.parentAbsolutePathInfo=le(t,e.parentPathInfo)}}const de=new WeakMap,ue=new WeakMap;class fe{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]===o?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAbsoluteAddress=he(t,e)}}function he(t,e){if(null===e){let e=ue.get(t);return void 0!==e||(e=new fe(t,null),ue.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 fe(t,e),n.set(t,o)),o}}const pe=new WeakMap;function me(t,e){null===e?pe.delete(t):pe.set(t,e)}function ge(t){return pe.get(t)||null}const ye=new Map;function be(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=ye.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,ye.set(s,r),r}function we(t,e,n){return e<0||e>=n?null:t.at(e-n)}function ve(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const Ne=new WeakMap;function Se(t){const e=Kt(t.node);if(null===e)return null;let n=Ne.get(e);if(void 0===n)n=new WeakMap,Ne.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=be(e.pathInfo,t.statePathInfo);return n>0&&(o=we(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const Ie=new WeakMap;function xe(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=ge(n);null===e?nt(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function $e(t,e){let n=null;if(n=Ie.get(t)||null,null!==n)return n;const o=xe(t,e),s=Se(t),r=ti(o,t.stateName);null===r&&nt(`State element with name "${t.stateName}" not found for binding.`);return n=he(le(r,t.statePathInfo),s),Ie.set(t,n),n}function Pe(t){Ie.delete(t)}const _e=new WeakMap;function Ae(t,e){const n=_e.get(t);void 0===n?_e.set(t,e):n instanceof Set?n.add(e):n!==e&&_e.set(t,new Set([n,e])),null!==Xt&&Xt({type:"state:binding-added",absoluteAddress:t,binding:e})}function ke(t,e){const n=_e.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&_e.delete(t),null!==Xt&&Xt({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const Ce=new WeakMap;function Ee(t,e,n){let o=Ce.get(t);void 0===o&&(o=new WeakMap,Ce.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!==Xt&&Xt({type:"state:binding-added",absoluteAddress:he(t,e),binding:n})}function Me(t,e,n){const o=Ce.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!==Xt&&Xt({type:"state:binding-removed",absoluteAddress:he(t,e),binding:n}))}function Te(t){const e=_e.get(t);return void 0!==e?e:null!==t.listIndex?Ce.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const Oe=new WeakMap,Re=new WeakMap;class De{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]===o?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=Le(t,e)}}function Le(t,e){if(null===e){let e=Re.get(t);return void 0!==e||(e=new De(t,null),Re.set(t,e)),e}{let n=Oe.get(e);void 0===n&&(n=new WeakMap,Oe.set(e,n));let o=n.get(t);return void 0!==o||(o=new De(t,e),n.set(t,o)),o}}const je=new WeakMap;function We(t){let e=null;if(e=je.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=Se(t);null===n&&nt(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=Le(t.statePathInfo,n)}else e=Le(t.statePathInfo,null);return je.set(t,e),e}function Be(t){je.delete(t)}function Fe(){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 ze=new Map,qe=Fe();function Ue(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.stateName}::${t.statePathName}::${e}::${n}`}function He(t){let e="input";for(const n of t.propModifiers)n.startsWith(h)&&(e=n.slice(2));return e}function Ve(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(l)){const s=He(t),r=Ue(t,s);let i=ze.get(r);return void 0===i&&(e=t.stateName,n=t.statePathName,o=t.inFilters,i=t=>{const s=t.target;if(null===s)return void console.warn("[@wcstack/state] event.target is null.");if("checkbox"!==s.type)return void console.warn("[@wcstack/state] event.target is not a checkbox input element.");const r=s.checked;let i=s.value;for(const t of o)i=t.filterFn(i);const a=ti(s.getRootNode(),e);null===a&&nt(`State element with name "${e}" not found for two-way binding.`);const l=Kt(s);a.createState("writable",t=>{t[te](l,()=>{let e=t[n];if(Array.isArray(e))if(r)-1===e.indexOf(i)&&(t[n]=e.concat(i));else{const o=e.indexOf(i);-1!==o&&(t[n]=e.toSpliced(o,1))}else t[n]=r?[i]:[]})})},ze.set(r,i)),t.node.addEventListener(s,i),qe.add(r,t),!0}var e,n,o;return!1}function Ge(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function Ke(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)Ge(t)&&Promise.resolve(t).catch(t=>{console.error(`[wcstack/state] ${e} rejected.`,t)})}class Je{_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 Xe extends Je{_ownerStateName;constructor(t,e){super(t),this._ownerStateName=e??null}emit(...t){return null!==Xt&&Xt({type:"state:token-emit",kind:"event",stateName:this._ownerStateName,tokenName:this.name,args:t,subscriberCount:this.size}),super.emit(...t)}}const Ye=new WeakMap;function Qe(t,e){let n=Ye.get(t);void 0===n&&(n=new Map,Ye.set(t,n));let o=n.get(e);return void 0===o&&(o=new Xe(e,t.name),n.set(e,o)),o}function Ze(t){Ye.delete(t)}const tn=new WeakMap;function en(t){if(t.propSegments[0]!==p)return!1;const e=t.node,n=G(e),o=J(e);if(null!==n&&void 0===o?.get(n))return null===o&&nt(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(tn.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||nt('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===G(t)?null:Y(t)}(e);null===r&&nt(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const l=r.knownProperties.get(s);void 0===l&&nt(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${ct(s,r.knownProperties.keys())}`);const c=l.event,d=t.statePathName,u=t.stateName,f=t.propModifiers,h=t=>{f.includes(i)&&t.preventDefault(),f.includes(a)&&t.stopPropagation();const n=ti(e.getRootNode(),u);null===n&&nt(`State element with name "${u}" not found for eventToken handler.`),n.eventTokenNames.has(d)||nt(`[wcs/token-undeclared] eventToken "${d}" is not declared in $eventTokens of state "${u}".${ct(d,n.eventTokenNames)}${dt}`);const o=Kt(e);n.createStateAsync("writable",async e=>{Ke(e[te](o,()=>{const s=null!==o?ve(o.listIndex,o.pathInfo.wildcardCount):[];return Qe(n,d).emit(e,t,...s)}),`$on."${d}" of state "${u}"`)})};return e.addEventListener(c,h),tn.set(t,{eventName:c,handler:h}),!0}class nn extends Je{_ownerStateName;constructor(t,e){super(t),this._ownerStateName=e??null}emit(...t){return null!==Xt&&Xt({type:"state:token-emit",kind:"command",stateName:this._ownerStateName,tokenName:this.name,args:t,subscriberCount:this.size}),super.emit(...t)}}function on(t){return t instanceof nn}const sn=new Map,rn=Fe();function an(t){const e=t.propModifiers.filter(t=>t===i||t===a).sort().join(",");return`${t.stateName}::${t.statePathName}::${e}`}const ln=(t,e,n,o)=>s=>{n.includes(i)&&s.preventDefault(),n.includes(a)&&s.stopPropagation();const r=s.target,l=ti(r.getRootNode(),t);null===l&&nt(`State element with name "${t}" not found for event handler.`);const c=Kt(r),d=e.startsWith(A+".");l.createStateAsync("writable",async n=>{Ke(n[te](c,()=>{const r=null!==c?ve(c.listIndex,c.pathInfo.wildcardCount):[];if(d){const t=n[ee](Le(o,null));return on(t)||nt(`Event binding "${e}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),t.emit(s,...r)}const i=n[e];return"function"!=typeof i&&nt(`Handler "${e}" is not a function on state "${t}".`),Reflect.apply(i,n,[s,...r])}),`"${e}" of state "${t}"`)})};function cn(t){if(!t.propName.startsWith(h))return!1;const e=an(t);let n=sn.get(e);void 0===n&&(n=ln(t.stateName,t.statePathName,t.propModifiers,t.statePathInfo),sn.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),rn.add(e,t),!0}const dn=new Map,un=Fe();function fn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.stateName}::${t.statePathName}::${e}::${n}`}function hn(t){let e="input";for(const n of t.propModifiers)n.startsWith(h)&&(e=n.slice(2));return e}function pn(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(l)){const s=hn(t),r=fn(t,s);let i=dn.get(r);return void 0===i&&(e=t.stateName,n=t.statePathName,o=t.inFilters,i=t=>{const s=t.target;if(null===s)return void console.warn("[@wcstack/state] event.target is null.");if("radio"!==s.type)return void console.warn("[@wcstack/state] event.target is not a radio input element.");if(!1===s.checked)return;let r=s.value;for(const t of o)r=t.filterFn(r);const i=ti(s.getRootNode(),e);null===i&&nt(`State element with name "${e}" not found for two-way binding.`);const a=Kt(s);i.createState("writable",t=>{t[te](a,()=>{t[n]=r})})},dn.set(r,i)),t.node.addEventListener(s,i),un.add(r,t),!0}var e,n,o;return!1}const mn=new Set(["radio","checkbox"]),gn=new Set(["value","valueAsNumber","valueAsDate"]);function yn(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(mn.has(t)&&"checked"===e)return!0;if(gn.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=G(n);if(null!==s){const t=J(n)?.get(s);void 0===t&&nt(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=Y(n);if(o?.knownProperties.has(e))return!0}return!1}let bn=1,wn=1,vn=1;const Nn=new WeakMap;function Sn(t,e,n,o){let s=Nn.get(t);void 0===s&&(s=new Map,Nn.set(t,s));const r=function(t,e,n){return`${e}::${n}::${t}`}(e,n,o);let i=s.get(r);return void 0===i&&(i=bn++,s.set(r,i)),i}function In(t,e){return"to-element"===e?2*t:2*t+1}const xn=new Set;function $n(t){return{transactionId:wn++,originBindingId:t,visitedEdges:xn,hop:0}}function Pn(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 _n=null;function An(){return _n}function kn(t,e){const n=_n;_n=t;try{return e()}finally{_n=n}}const Cn=[];let En=!1;const Mn=new Map,Tn=Fe(),On=new WeakMap,Rn=t=>t.detail;function Dn(t,e,n,o){const s=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.stateName}::${t.propName}::${t.statePathName}::${e}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function Ln(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=G(t.node);if(null!==n){const o=J(t.node)?.get(n);void 0===o&&nt(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Y(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(h)&&(e=n.slice(2));return e}function jn(t){if(null!==G(t.node)){const e=Y(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??Rn}return null}function Wn(t){if(null===G(t.node))return!1;const e=Y(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}const Bn=(t,e,n,o,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(!(e in a))return void console.warn(`[@wcstack/state] Property "${e}" does not exist on target element.`);l=a[e]}let c=l;for(const t of o)c=t.filterFn(c);const d=On.get(a)?.get(e);if(void 0!==d)for(const t of d)t(c);let u=null;{const o=Sn(a,e,t,n),s=function(t,e){for(let n=Cn.length-1;n>=0;n--){const o=Cn[n];if(o.node===t&&o.receipt.member===e)return o.receipt}return null}(a,e);if(null!==s&&Object.is(s.writtenValue,l))return void(null!==Xt&&Xt({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:In(o,"to-state"),node:a,member:e}));const r=In(o,"to-state"),i=An();if(null!==i&&i.visitedEdges.has(r))return void(null!==Xt&&Xt({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=Pn(i??$n(o),r)}const f=ti(a.getRootNode(),t);null===f&&nt(`State element with name "${t}" not found for two-way binding.`);const h=Kt(a),p=()=>{r&&(En=!0);try{f.createState("writable",t=>{t[te](h,()=>{t[n]=c})})}finally{r&&(En=!1)}};null!==u?kn(u,p):p()};const Fn=new WeakMap;function zn(t,e){const n=Fn.get(t);return n?n.get(e)??null:null}const qn=new WeakMap;function Un(t,e){qn.set(t,e)}function Hn(t){return qn.get(t)??null}function Vn(t){let e=t;for(;;){if(null==e||!0!==e.hasMappedComponentState)return null;const t=e.boundComponent;if(null==t)return null;const n=Kt(t)?.listIndex;if(null!=n)return n;e=Hn(t)}}function Gn(t){return Vn(t)?.length??0}function Kn(t,e){return e.wildcardCount+Gn(t)}function Jn(t,e){return e??Vn(t)}const Xn=new WeakMap,Yn=new WeakMap,Qn=new WeakMap,Zn=new WeakMap;function to(t,e){return{innerAbsPathInfo:le(t,U(e.propSegments.slice(1).join(n))),outerAbsPathInfo:$e(e).absolutePathInfo}}function eo(t,e,o=!0){let s=Xn.get(t);if(void 0===s&&(s=new Map,Xn.set(t,s)),s.has(e))return s.get(e);let r=Yn.get(t);void 0===r&&(r=new Map,Yn.set(t,r));const i=Qn.get(t);if(void 0===i)return null;let a=null;for(const t of i)if(e.pathInfo.cumulativePathInfoSet.has(t.innerAbsPathInfo.pathInfo)){t.innerAbsPathInfo.pathInfo.segments.length===e.pathInfo.segments.length&&nt("Duplicate mapping rule for web component."),a=t;break}if(null===a)return null;const l=Zn.get(a);void 0===l&&nt("Binding not found for primary mapping rule on web component.");const c=e.pathInfo.segments.slice(a.innerAbsPathInfo.pathInfo.segments.length),d=U(a.outerAbsPathInfo.pathInfo.segments.concat(c).join(n)),u=ti(t.getRootNode(),l.stateName);null===u&&nt(`State element with name "${l.stateName}" not found for web component.`);const f=le(u,d);if(!o)return f;s.set(e,f),r.set(f,e);const h=[l.propSegments[0],...e.pathInfo.segments],p={...l,propName:h.join(n),propSegments:h,statePathName:f.pathInfo.path,statePathInfo:f.pathInfo},m=Bo(l);return null===m||f.pathInfo.wildcardCount>0&&null===Se(p)||m.initialize([p],{registerAddress:!0}),f}function no(t,e){const n=oo(t,e);if(null===n||n.stateElement===t)return null;return Kn(t,e)!==Kn(n.stateElement,n.pathInfo)?null:n}function oo(t,e){if(!0!==t.hasMappedComponentState)return null;const n=t.boundComponent;if(null==n)return null;return eo(n,le(t,e),!1)}const so=new WeakSet;function ro(t){so.add(t)}function io(t){return!!so.has(t)&&(so.delete(t),!0)}const ao=new WeakSet;function lo(t){ao.add(t)}function co(t){return!!ao.has(t)&&(ao.delete(t),!0)}let uo=0;function fo(){uo--}function ho(){return uo>0}class po{registry;entries=new Map;constructor(t){this.registry=t}wait(t,e,n=()=>{}){const o=t.toLowerCase();let s=this.entries.get(o);void 0===s&&(s={waiters:new Set},this.entries.set(o,s),this.registry.whenDefined(o).then(()=>this.settle(o,null),t=>this.settle(o,t)));const r={active:!0,resolve:e,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(t){return this.entries.get(t.toLowerCase())?.waiters.size??0}settle(t,e){const n=this.entries.get(t);if(void 0===n)return;this.entries.delete(t);const o=Array.from(n.waiters);n.waiters.clear();for(const t of o)t.active&&(t.active=!1,null===e?t.resolve():t.reject(e))}}const mo=new WeakMap;function go(t){let e=mo.get(t);return void 0===e&&(e=new po(t),mo.set(t,e)),e}function yo(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!==c&&s!==d&&nt(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&nt(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}const bo=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),wo=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function vo(t,e){return"state"===t&&"call"===e?bo:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function No(t){const e=null===(n=yo(t,c))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:nt(`Invalid init modifier value "${n}".`);var n;const o=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":nt(`Invalid sync modifier value "${t}".`)}(yo(t,d));if("event"===t.bindingType)return null!==e&&"none"!==e&&nt("Event bindings only allow init=none."),"call"===o?wo:{authority:"none",syncOn:o,observable:!1,outputOnly:!1};if(t.propSegments[0]===m)return vo("state",o);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&nt(`Binding type "${t.bindingType}" does not support init=${e}.`),vo(e??"state",o);const s=Y(t.node);if(null===s)return vo(e??"state",o);const r=s.knownProperties.has(t.propName),i=s.declaredInputs.has(t.propName);r||i||nt(`Property "${t.propName}" is not declared by wcBindable.`);const a=e??(r&&!i?"element":"state");return(r&&i?new Set(["state","element","auto","none"]):r?new Set(["element","none"]):new Set(["state","none"])).has(a)||nt(`init=${a} is incompatible with wcBindable member "${t.propName}".`),"connect"!==o||r||nt(`sync=connect requires observable property "${t.propName}".`),{authority:a,syncOn:o,observable:r,outputOnly:r&&!i}}function So(t,e){return"auto"!==e?e:function(t){const e=ti(t.replaceNode.getRootNode(),t.stateName);null===e&&nt(`State element with name "${t.stateName}" not found for binding.`);const n=We(t);let o=!1;return e.createState("readonly",t=>{o=t[ne](n)}),o}(t)?"state":"element"}let Io=0,xo=0;const $o=new WeakMap,Po=new WeakMap,_o=new WeakMap,Ao=new WeakMap;function ko(t,e){const n=Ao.get(t);void 0!==n?n!==e&&(n instanceof Set?n.add(e):Ao.set(t,new Set([n,e]))):Ao.set(t,e)}function Co(t,e){const n=Ao.get(t);if(void 0!==n)if(n instanceof Set)for(const t of Array.from(n))e(t);else e(n)}function Eo(t,e){if(e(t),null!==t.firstChild)for(const n of Array.from(t.childNodes))Eo(n,e)}function Mo(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class To{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)io(t)||Eo(t,t=>{Co(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)co(t)&&!ho()||Eo(t,t=>{Co(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&pr(o)}}const Oo=new WeakMap;function Ro(t){let e=Oo.get(t);return void 0===e&&(e=new To(t),Oo.set(t,e)),e}function Do(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.stateName,t.statePathName,e,n,t.uuid??""].join("\0")}function Lo(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class jo{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=$o.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(Mo(e)&&Ro(e),null===this.rowPlan)for(const n of t){const t=$o.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){const e=$o.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=$o.get(t);return e?.session===this?e:null}addTeardown(t,e){const n=$o.get(t);return!(void 0===n||!this.isAlive(n,n.generation))&&(Lo(n,e),!0)}deferUntilDefined(t,e,n,o=()=>{}){const s=J(t);null===s&&nt(`CustomElementRegistry is unavailable for <${e}>.`),this.observe(t),ko(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=go(s).wait(e,()=>{if(a())try{X(s,t),n()}catch(t){o(t)}},t=>{a()&&o(t)}),()=>{a()&&r.cancel?.()}}disposeBinding(t){const e=$o.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&&(ke(t.address,t.info),t.address=null),t.phase="disposed",t.teardowns=null;this.records.clear()}observe(t){const e=function(t){const e=t.getRootNode();return Mo(e)?e:null}(t);null!==e&&Ro(e)}handleMutations(t,e,n){for(const n of e)Eo(n,e=>{t.contains(e)||this.handleRemovedNode(e)});const o=[];for(const e of n)Eo(e,e=>{t.contains(e)&&this.handleAddedNode(e,o)});o.length>0&&pr(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=$o.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=_o.get(e);void 0===t&&(t=Do(e),_o.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;ko(n,this);const o=this.knownMapFor(n);let s=_o.get(t);void 0===s&&(s=Do(t),_o.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;ko(i,this),this.addKnownRowBinding(i,s,t),this.optionsByBinding.set(s,n);const a={id:++Io,info:s,generation:++xo,phase:"active",teardowns:null,session:this,anchor:i,options:n,address:null,patternPathInfo:null,patternListIndex:null,outerPatternPathInfo:null,outerPatternPathInfosRest: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($o.set(s,a),this.records.add(a),r.isEvent){try{cn(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=$o.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=++xo,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{cn(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:++Io,info:t,generation:++xo,phase:"discovered",teardowns:null,session:this,anchor:t.replaceNode,options:o,address:null,patternPathInfo:null,patternListIndex:null,outerPatternPathInfo:null,outerPatternPathInfosRest: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};$o.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;cn(e)?t.eventAttached=!0:e.propSegments[0]!==p?(pn(e)&&Lo(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(l)){const e=hn(t),n=fn(t,e),o=dn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==un.countOf(n)&&(un.remove(n,t)&&dn.delete(n),!0))}return!1}(e)),Ve(e)&&Lo(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(l)){const e=He(t),n=Ue(t,e),o=ze.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==qe.countOf(n)&&(qe.remove(n,t)&&ze.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(yn(e.node,e.propName)&&-1===e.propModifiers.indexOf(l)){const n=function(t,e,n){let o=On.get(t);void 0===o&&(o=new Map,On.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&&On.delete(t)}}(e.node,e.propName,e=>{this.isAlive(t,t.generation)&&(t.eventSequence+=1,t.hasProducerValue=!0,t.producerValue=e)});Lo(t,n)}!function(t){const e=G(t.node);if(null!==e){const n=J(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&nt(`CustomElementRegistry is unavailable for <${e}>.`))}if(yn(t.node,t.propName)&&-1===t.propModifiers.indexOf(l)){const e=Ln(t),n=jn(t),o=Wn(t),s=Dn(t,e,null!==n,o);let r=Mn.get(s);void 0===r&&(r=Bn(t.stateName,t.propName,t.statePathName,t.inFilters,n,o),Mn.set(s,r)),t.node.addEventListener(e,r),Tn.add(s,t)}}(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{en(e)&&Lo(t,()=>function(t){if(t.propSegments[0]!==p)return!1;const e=tn.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),tn.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=G(t.info.node);if(null===n)return void e();const o=J(t.info.node);if(null===o&&nt(`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=go(o).wait(n,()=>{if(this.isAlive(t,s))try{X(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))});Lo(t,r)}settleInitialRecord(t){if(!t.initialSettled&&t.options.registerAddress){t.phase="synchronizing";try{const e=No(t.info),n=So(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 uo++;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,fo()),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=ti(t.node.getRootNode(),t.stateName);null===o&&nt(`State element with name "${t.stateName}" not found for initial binding sync.`);const s=Kt(t.node);o.createState("writable",e=>{e[te](s,()=>{e[t.statePathName]=n})})}(t.info,r))}settleConnectedSnapshot(t){if(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=Se(n);if(null!==o){const i=ti(xe(n,e),n.stateName);null===i&&nt(`State element with name "${n.stateName}" not found for binding.`);const a=le(i,n.statePathInfo);Ee(a,o,n),t.patternPathInfo=a,t.patternListIndex=o;const l=(s=i,0===(r=n.statePathInfo).wildcardCount?null:no(s,r));if(null!==l){Ee(l,o,n),t.outerPatternPathInfo=l;const e=function(t){let e=null,n=t.stateElement,o=t.pathInfo;for(;;){const t=no(n,o);if(null===t)return e;(e??=[]).push(t),n=t.stateElement,o=t.pathInfo}}(l);if(null!==e){for(let t=0;t<e.length;t++)Ee(e[t],o,n);t.outerPatternPathInfosRest=e}}}else{const o=$e(n,e);Ae(o,n),t.address=o}var s,r;if(!t.options.registerPathInfo)return;const i=ti(n.replaceNode.getRootNode(),n.stateName);null===i&&nt(`State element with name "${n.stateName}" not found for binding.`),"event"!==n.bindingType&&i.setPathInfo(n.statePathName,n.bindingType)}isAlive(t,e){return t.generation===e&&$o.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,fo());const e=t.info;if(null!==t.address)try{ke(t.address,e),t.address=null,Be(e),Pe(e)}catch{}else if(null!==t.patternListIndex){if(null!==t.outerPatternPathInfo){try{Me(t.outerPatternPathInfo,t.patternListIndex,e)}catch{}t.outerPatternPathInfo=null}if(null!==t.outerPatternPathInfosRest){const n=t.outerPatternPathInfosRest;for(let o=0;o<n.length;o++)try{Me(n[o],t.patternListIndex,e)}catch{}t.outerPatternPathInfosRest=null}try{Me(t.patternPathInfo,t.patternListIndex,e),t.patternPathInfo=null,t.patternListIndex=null,Be(e),Pe(e)}catch{}}if(t.twowayAttached){t.twowayAttached=!1;try{!function(t){const e=G(t.node);if(null!==e){const n=J(t.node),o=n?.get(e);if(void 0===o)return}if(yn(t.node,t.propName)&&-1===t.propModifiers.indexOf(l)){const e=Ln(t),n=Dn(t,e,null!==jn(t),Wn(t)),o=Mn.get(n);if(void 0===o)return;t.node.removeEventListener(e,o),Tn.remove(n,t)&&Mn.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(h))return!1;const e=an(t),n=sn.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);t.node.removeEventListener(o,n),0!==rn.countOf(e)&&(rn.remove(e,t)&&sn.delete(e))}(e)}catch{}}}}function Wo(t){let e=Po.get(t);return void 0===e&&(e=new jo(t),Po.set(t,e)),e}function Bo(t){return $o.get(t)?.session??null}const Fo=new WeakMap;function zo(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const qo=Object.freeze([]);const Uo=new WeakMap;const Ho=new WeakMap;function Vo(t){return Ho.get(t)??[]}function Go(t,e){Ho.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 Ko=0;function Jo(){return`u${(Ko++).toString(36)}`}let Xo=0;class Yo{uuid=Jo();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=Xo}get index(){return this._index}set index(t){this._index=t,this._version=++Xo,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=Xo),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 Qo(t,e){return new Yo(t,e)}const Zo=new WeakMap;function ts(t){return Zo.get(t)||null}function es(t,e){null!==e?Zo.set(t,e):Zo.delete(t)}const ns=new WeakMap,os=Object.freeze([]),ss=new Set;function rs(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:os,s=Array.isArray(n)&&n.length>0?n:os,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:os,o=Array.isArray(e)&&e.length>0?e:os;let s=ns.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=ts(o)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:ss,deleteIndexSet:new Set(i),addIndexSet:ss};let e=ts(s);if(0===o.length){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=Qo(t,n);e.push(o)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:ss,deleteIndexSet:ss,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:ss,deleteIndexSet:ss,addIndexSet:ss};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=Qo(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=ns.get(t);o||(o=new WeakMap,ns.set(t,o)),o.set(e,n)}(o,s,a),es(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 is(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 as=new WeakMap;function ls(t){return as.get(t)??[]}function cs(t,e){as.set(t,e)}const ds=new WeakMap;function us(t){return ds.get(t)??null}function fs(t,e){ds.set(t,e)}const hs=new WeakMap;function ps(t){return hs.get(t)??[]}function ms(t,e){hs.set(t,e)}function gs(t,e){const n=ps(t);for(const t of n)Jt(t,e)}function ys(t,e,n){gs(t,e);const o=ls(t),s=us(t);null!==s&&s.activate(o,n.rootNode);for(const t of o){if(null===s){Ae($e(t),t)}(null===s||s.shouldApplyState(t))&&fr(t,n)}}function bs(t){if(!t.mounted)return;const e=ls(t),n=us(t);for(const t of e)if(null!==n)n.disposeBinding(t);else{ke($e(t),t)}!function(t){const e=ps(t);for(const t of e)Jt(t,null)}(t)}const ws=new WeakMap,vs=Object.freeze(new Set);function Ns(t,e){const n=ws.get(t);n?n.add(e):ws.set(t,new Set([e]))}function Ss(t){const e=ws.get(t);return void 0!==e?e:vs}function Is(t,e){const n=ws.get(t);n&&(n.delete(e),0===n.size&&ws.delete(t))}const xs=new Set(["if","elseif","else","for"]);class $s{_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)lo(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())n.nextSibling!==t&&(lo(t),e.insertBefore(t,n.nextSibling)),n=t}this._mounted=!0}tryDestroy(){const t=us(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRecords();for(const t of this._childNodeArray)ro(t),null!==t.parentNode&&t.parentNode.removeChild(t);const e=ls(this);for(const t of e)if(xs.has(t.bindingType)){const e=Ss(t.node);for(const t of e)t.tryDestroy()||t.unmount()}return this._mounted=!1,!0}unmount(){us(this)?.dispose();for(const t of this._childNodeArray)ro(t),null!==t.parentNode&&t.parentNode.removeChild(t);const t=ls(this);for(const e of t){if(xs.has(e.bindingType)){const t=Ss(e.node);for(const e of t)e.unmount()}Be(e),Pe(e)}this._mounted=!1}}function Ps(t){let n=t.topLevelStructural;return void 0===n&&(n=t.topLevelStructural=function(t){const n=new RegExp(`^@@(?:${e.commentForPrefix}|${e.commentIfPrefix}|${e.commentElseIfPrefix}|${e.commentElsePrefix}):`);for(let e=t.firstChild;null!==e;e=e.nextSibling)if(e.nodeType===Node.COMMENT_NODE&&n.test(e.data))return!0;return!1}(t.fragment)),n}function _s(t){const e=document.createDocumentFragment(),n=new $s(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 As(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=it(o,s[t].nodePath);null===e&&nt(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),Ht(e),F(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 jo;return n.initializeRow(t,e),n}(n,a),d=new $s(o);return fs(d,c),cs(d,a),Go(d,l),ms(d,r),Ns(t.node,d),d}function ks(n){void 0!==n.uuid&&null!==n.uuid||nt("BindingInfo.uuid is null.");const o=Dt(n.uuid);o||nt(`Fragment with UUID "${n.uuid}" not found.`);const s=!t()&&Ps(o);let r=o.rowPlan;if((void 0===r||null!==r&&r.directional!==e.enableDirectionalInitialSync)&&(r=o.rowPlan=function(t){const n=e.enableDirectionalInitialSync,o=[],s=t.nodeInfos;for(let e=0;e<s.length;e++){const n=s[e],r=it(t.fragment,n.nodePath);if(null===r)return null;for(const t of n.parseBindTextResults){const n=t.bindingType;if("text"!==n&&"prop"!==n&&"event"!==n)return null;const s=t.propSegments[0];if(s===m||s===p)return null;if("text"===n){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==G(r))return null;if("prop"===n&&yn(r,t.propName))return null;let i;try{i=No({...t,node:r,replaceNode:r})}catch{return null}if(i.observable||"auto"===i.authority)return null;o.push({nodeIndex:e,template:t,isEvent:"event"===n,isIndexBinding:t.statePathName in v,policy:i,authority:i.authority})}}return{directional:n,slots:o}}(o)),null!==r)return As(n,o,r);const i=document.importNode(o.fragment,!0),a=function(t,e){const[n,o]=function(t,e){const n=[],o=[];for(const s of e){const e=it(t,s.nodePath);if(null===e&&nt(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),zt.has(e))continue;const r=qt(e,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(e)}return[n,o]}(t,e),s=new jo,r=s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:r,bindingSession:s}}(i,o.nodeInfos);s&&function(t,e){t.appendChild(document.createComment(`wcs-row-end:${e}`))}(i,n.uuid);const l=new $s(i,s);fs(l,a.bindingSession),cs(l,a.bindingInfos);const c=[];for(const t of a.bindingInfos)t.statePathName in v&&c.push(t);return Go(l,c),ms(l,a.nodes),Ns(n.node,l),l}const Cs=new WeakMap,Es=new WeakMap,Ms=new WeakMap,Ts=new WeakMap;function Os(t,e,n){!function(t,e,n){let o=Es.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,Es.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function Rs(t,e){Cs.set(t,e)}function Ds(t,e){let n=Ms.get(t.node);void 0===n&&(n=[],Ms.set(t.node,n)),n.length<1e3?n.push(e):Is(t.node,e)}function Ls(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 js(e,n,o){const s=Boolean(o);let r;const i=Ss(e.node);r=0===i.size?ks(e):i.values().next().value;const a=t(),l=e.uuid??"",c=e.bindingType;if(s||(bs(r),r.unmount()),s){if(a){const t=document.createComment(`@@wcs-${c}-start:${l}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),r.mountAfter(t);const n=document.createComment(`@@wcs-${c}-end:${l}:${e.statePathName}`),o=r.lastNode??t;o.parentNode.insertBefore(n,o.nextSibling)}else r.mountAfter(e.node);ys(r,Kt(e.node),n)}}const Ws=new WeakMap;function Bs(t){return Ws.get(t)??[]}const Fs=new Set;const zs={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 qs(e,n,o){if(void 0===o)return;const s=e.node,r=e.propSegments;if(1===r.length){const a=r[0];if(s[a]!==o){const t=()=>{let t=!1;try{s[a]=o,t=!0}catch(t){}if(t){const t=function(t,e){const n=G(t);if(null===n)return null;const o=J(t)?.get(n);if(void 0===o)return null;const s=Y(t)?.declaredInputs.get(e);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(s,a);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)}(s,t,o)}catch(t){}}};if(yn(s,a)){const r=Sn(s,a,e.stateName,e.statePathName),i=In(r,"to-element"),l=n?.propagationContextByBinding?.get(e)??An()??$n(r);if(l.visitedEdges.has(i))null!==Xt&&Xt({type:"propagation:suppressed",reason:"visited-edge",transactionId:l.transactionId,edgeId:i,node:s,member:a});else{const e=Pn(l,i);kn(e,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:vn++,writtenValue:n};Cn.push({receipt:i,node:t});try{return r()}finally{Cn.pop()}}(s,a,o,r,e.transactionId,t))}}else t()}if(t()){const t=zs[a];t?t(s,o):(!function(t,e,n){let o=Ws.get(t);o||(o=[],Ws.set(t,o));const s=o.find(t=>t.propName===e);s?s.value=n:o.push({propName:e,value:n})}(s,a,o),i=s,Fs.add(i))}return}var i;const a=r[0];let l=s[a];for(let t=1;t<r.length-1;t++){const e=r[t];if(null==l)return;l=l[e]}if(l[r[r.length-1]]!==o){if(Object.isFrozen(l))return;try{l[r[r.length-1]]=o}catch(t){}}}const Us=new WeakSet;function Hs(t,e,o){const s=t.node,r=t.propSegments;r.length<=1&&nt(`Invalid propSegments for web component binding: ${r.join(n)}`);const[i,...a]=r,l=zn(s,i);null===l&&nt(`State element not bound to "${i}" on web component.`),!1!==l.hasRootNode&&l.createState("readonly",t=>{t.$postUpdate(a.join(n))})}const Vs=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Gs=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});function Ks(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 Js(t,e,o){const s=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+n:"";for(const t of o){if(r.length>0&&!t.startsWith(r))continue;const e=t.slice(r.length);e.length>0&&-1===e.indexOf(n)&&s.push(e)}return s}const Xs={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing"},Ys={binding:"Bound path",watch:"$watch path"};function Qs(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}.${dt}`}function Zs(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.${dt}`}const tr=new WeakMap;function er(t,e,s,r){if("internal"===r||void 0===e)return;if(s.startsWith("$"))return;if(!0===t.hasMappedComponentState)return;const i=U(s).segments;if("binding"===r&&i.length<2)return;if(function(t,e){let n=tr.get(t);return void 0===n&&(n=new Set,tr.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,s))return;const a=function(t,e,s){if(void 0!==Ks(t,e))return Gs;const r=U(e).segments;let i=t,a="";for(let e=0;e<r.length;e++){const l=r[e],c=a;if(a=0===e?l:a+n+l,e>0&&e<r.length-1&&void 0!==Ks(t,a))return Vs;if(Object(i)!==i)return Vs;if(l===o){if(!Array.isArray(i)||0===i.length)return Vs;i=i[0];continue}const d=Ks(i,l);if(void 0===d)return{existence:"missing",missingSegment:l,candidates:Js(i,c,s)};if("function"==typeof d.get)return e===r.length-1?Gs:Vs;i=d.value}return Gs}(e,s,t.getterPaths);"missing"===a.existence&&(console.warn(`[@wcstack/state] [${Xs[r]}] ${Ys[r]} "${s}" does not resolve on state "${t.name}": "${a.missingSegment}" is not declared.${ct(a.missingSegment,a.candidates)} Updates to this path will be silently dropped.${dt}`),null!==Xt&&Xt({type:"state:path-unresolved",source:r,stateName:t.name,path:s,missingSegment:a.missingSegment}))}function nr(t,e){const n=We(e);if(n.pathInfo.path in v){const t=Kt(e.node);return null===t&&nt(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&nt("ListIndex not found for loopContext:");const n=v[e];void 0===n&&nt(`Invalid index name: ${e}`);const o=we(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&nt(Zs(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[ee](n)}const or=new WeakSet;function sr(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const rr=Object.freeze({[g]:function(t,e,n){const o=t.node,s=t.propSegments[1];"boolean"!=typeof n&&nt("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[y]:function(t,e,n){const o=t.node,s=t.propSegments[1];o.getAttribute(s)!==n&&o.setAttribute(s,n)},[b]:function(t,e,n){const o=t.propSegments[1],s=t.node.style;s[o]!==n&&(s[o]=n)},[m]:function(t,e,n){on(n)||nt("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=Uo.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||nt('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=G(t);if(null===e)return null;const n=J(t)?.get(e);return void 0===n&&nt(`Custom element <${e}> is not defined for command binding.`),Y(t)}(r);null===a&&nt(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||nt(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${ct(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),Uo.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 Uo.delete(t);const o=n[i];return"function"!=typeof o&&nt(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),Uo.set(t,{token:o,unsubscribe:c,elementRef:l})}}),ir={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!Us.has(e.replaceNode)){Us.add(e.replaceNode);const t=e.replaceNode.parentNode;if(t){const n=e.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);t.insertBefore(o,e.replaceNode),t.insertBefore(s,e.replaceNode.nextSibling)}}},for:function(e,n,s){const r=e.statePathInfo,i=Se(e),a=$e(e),l=Qt(a),c=rs(Jn(n.stateElement,i),l,s);n.newListValueByAbsAddress.set(a,Array.isArray(s)?s:[]);const d=Array.isArray(l)&&l.length===c.deleteIndexSet.size&&c.deleteIndexSet.size>0;if(d&&null!==e.node.parentNode){let t=Ts.get(e.node);if(void 0===t){const n=Cs.get(e.node)||e.node;t=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}(e.node,n),Ts.set(e.node,t)}if(t){const t=e.node.parentNode;t.textContent="",t.appendChild(e.node)}}let u=Es.get(e.node),f=d?1e3-function(t){return Ms.get(t.node)||[]}(e).length:Number.POSITIVE_INFINITY;if(void 0!==u){for(const t of c.deleteIndexSet){const n=u.get(t);void 0!==n&&(f<=0&&n.tryDestroy()?Is(e.node,n):(bs(n),n.unmount(),Ds(e,n),f-=1),d||u.delete(t))}d&&(Es.delete(e.node),u=void 0)}let h=e.node;const p=U(r.path+"."+o),m=n.stateElement.loopContextStack,g=is(c);let y=null;c.newIndexes.length==c.addIndexSet.size&&c.newIndexes.length>0&&h.isConnected&&(y=document.createDocumentFragment(),me(y,n.rootNode));const b=t(),w=e.uuid??"",v=Ms.get(e.node);for(const t of c.newIndexes){let o;if(c.addIndexSet.has(t)){const s=Le(p,t);m.createLoopContext(s,s=>{if(o=void 0!==v?v.pop():void 0,void 0===o&&(o=ks(e)),null!==y)b&&y.appendChild(document.createComment(`@@wcs-for-start:${w}:${r.path}:${t.index}`)),o.appendTo(y),b&&y.appendChild(document.createComment(`@@wcs-for-end:${w}:${r.path}:${t.index}`));else{if(h.nextSibling!==o.firstNode){if(b){const e=document.createComment(`@@wcs-for-start:${w}:${r.path}:${t.index}`);h.parentNode.insertBefore(e,h.nextSibling),h=e}o.mountAfter(h)}if(b){const e=document.createComment(`@@wcs-for-end:${w}:${r.path}:${t.index}`),n=o.lastNode??h;n.parentNode.insertBefore(e,n.nextSibling)}}ys(o,s,n)}),void 0===o&&nt(`Content not found for ListIndex: ${t.index} at path "${r.path}"`)}else{if(o=void 0!==u?u.get(t)??null:null,c.changeIndexSet.has(t)){const t=Vo(o);for(const e of t)fr(e,n)}null===o&&nt(`Content not found for ListIndex: ${t.index} at path "${r.path}"`);const e=!o.mounted;if(null!==g&&g.has(t)&&Ls(h,o.firstNode)||h.nextSibling===o.firstNode||o.mountAfter(h),e){const e=o,s=Le(p,t);m.createLoopContext(s,t=>{ys(e,t,n)})}}h=o.lastNode||h,void 0===u&&(u=new WeakMap,Es.set(e.node,u)),u.set(t,o)}Cs.set(e.node,h),null!==y&&(e.node.parentNode.insertBefore(y,e.node.nextSibling),me(y,null))},if:js,else:js,elseif:js,radio:function(t,e,n){const o=t.node,s=zo(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=zo(o.value,t.inFilters),r=Array.isArray(n)?n:qo;o.checked=r.includes(s)}},ar=new WeakMap,lr=new WeakMap,cr=new WeakMap;function dr(t){return t.propSegments.length>1&&(e=t.replaceNode,n=t.propSegments[0],!0===Fo.get(e)?.has(n));var e,n}function ur(t,e){const n=zo(nr(e.state,t),t.outFilters);if(!0===lr.get(t))return void e.deferredSelectBindings.push({binding:t,value:n});let o=ar.get(t);if(void 0===o){if(ar.has(t))return dr(t)?(o=Hs,ar.set(t,o)):o=qs,void o(t,e,n);if(o=ir[t.bindingType],void 0===o){const e=t.propSegments[0];if(o=rr[e],ar.set(t,o),void 0===o){G(t.replaceNode)?dr(t)?(o=Hs,ar.set(t,o)):o=qs:(o=qs,ar.set(t,o))}}if(o===qs){if("SELECT"===t.node.tagName){const o=t.propSegments[0];if("value"===o||"selectedIndex"===o)return e.deferredSelectBindings.push({binding:t,value:n}),void lr.set(t,!0)}}o(t,e,n)}else o(t,e,n)}function fr(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=$e(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=Bo(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==cr.get(t)){const e=G(t.replaceNode);if(e&&void 0===J(t.replaceNode)?.get(e))return void function(t,e){if(or.has(t))return;or.add(t);const n=()=>{or.delete(t);const e=Bo(t);(null===e||e.shouldApplyState(t))&&pr([t])},o=n=>{or.delete(t),sr(e,n)},s=Bo(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=J(t.replaceNode);if(null===r)return or.delete(t),void sr(e,new Error("CustomElementRegistry is unavailable."));go(r).wait(e,()=>{t.replaceNode.isConnected?n():or.delete(t)},o)}(t,e);cr.set(t,!0)}if(!0===e.sameRootVerified&&t.stateName===e.stateName)return void ur(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=ge(o),null===o&&nt("Root node for fragment not found for binding.")),t.stateName!==e.stateName||o!==e.rootNode){const n=ti(o,t.stateName);null===n&&nt(`State element with name "${t.stateName}" not found for binding.`),n.createState("readonly",s=>{const r={stateName:t.stateName,rootNode:o,stateElement:n,state:s,appliedBindingSet:e.appliedBindingSet,newListValueByAbsAddress:e.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:e.updatedAbsAddressSetByStateElement,deferredSelectBindings:e.deferredSelectBindings};ur(t,r)})}else ur(t,e)}function hr(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!==Xt&&Xt({type:"state:binding-apply-error",stateName:t.stateName,path:t.statePathName,bindingType:t.bindingType,error:e})}function pr(t,e){let n=0;const o=new Set,s=new Map,r=new Map,i=[];for(;n<t.length;){let a=t[n];const l=a.stateName;if(!1===a.replaceNode.isConnected){n++;continue}let c=a.replaceNode.getRootNode();c instanceof DocumentFragment&&!(c instanceof ShadowRoot)&&(c=ge(c),null===c&&nt("Root node for fragment not found for binding."));const d=ti(c,l);null===d&&nt(`State element with name "${l}" not found for binding.`),d.createState("readonly",u=>{const f={rootNode:c,stateName:l,stateElement:d,state:u,appliedBindingSet:o,newListValueByAbsAddress:s,updatedAbsAddressSetByStateElement:r,deferredSelectBindings:i,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{fr(a,f)}catch(t){hr(a,t)}n++;const e=t[n];if(!e)break;const o=e.replaceNode.getRootNode();if(e.stateName!==l||o!==f.rootNode)break;a=e}})}for(const{binding:t,value:n}of i)try{qs(t,{propagationContextByBinding:e},n)}catch(e){hr(t,e)}for(const[t,e]of s.entries())Zt(t,e);for(const[t,e]of r.entries())t.createState("writable",t=>{t[ie](Array.from(e))})}function mr(t,e){const[n,o,s]=Ut(t),r=Wo(t);for(const t of n)Jt(t,e);pr(r.initialize(o)),function(t,e,n){for(const o of t)n.deferUntilDefined(o.node,o.tagName,()=>{const t=Vt(o);0!==t.length&&(Jt(o.node,e),pr(n.initialize(t)))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,t)})}(s,e,r)}const gr=/\{\{\s*(.+?)\s*\}\}/g,yr=new Set(["SCRIPT","STYLE"]);function br(t){!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&&yr.has(t.parentElement.tagName)||wr(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),br(e.content)}else br(t.content)}function wr(t){const e=t.data;if(gr.lastIndex=0,!gr.test(e))return;gr.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=gr.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 vr;function Nr(){if(vr)return vr;const t=[],e=vt("not",t)(bt);return vr={filterName:"not",args:t,filterFn:e},vr}const Sr=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Ir(t,e){const s=e+n+o,r=t.indexOf("|"),i=t.indexOf("@");let a,l;if(-1!==r?(a=t.slice(0,r).trim(),l=t.slice(r)):-1!==i?(a=t.slice(0,i).trim(),l=t.slice(i)):(a=t.trim(),l=""),"."===a)a=s;else{if(!a.startsWith("."))return t;a=s+n+a.slice(1)}return l.length>0?a+l:a}function xr(t,e){const n=Sr.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+Ir(s,e)+r}function $r(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=Ir(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function Pr(t,e){return $r(t,e)}function _r(t,n){const o=e.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 e=t;e.data=xr(e.data,n);continue}const e=t;if(e instanceof HTMLTemplateElement)continue;const r=e.getAttribute(o);if(null!==r){const t=$r(r,n);t!==r&&e.setAttribute(o,t)}}}function Ar(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 kr(t){const e=[],n=Ft(t);for(const t of n){const n=Lt(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:Ar(o),parseBindTextResults:n})}return e}function Cr(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 Er=new Map([["for",e.commentForPrefix],["if",e.commentIfPrefix],["elseif",e.commentElseIfPrefix],["else",e.commentElsePrefix]]),Mr=Nr();function Tr(t,e){const n=e.outFilters;return{...e,outFilters:[...n,Mr],bindingType:t}}function Or(t,e,n,o){Cr(e),"string"==typeof o&&_r(e,o),Rr(t,e,o);return{fragment:e,parseBindTextResult:n,nodeInfos:kr(e)}}function Rr(t,n,o){const s=e.commentElsePrefix,r=Wt(n),i=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,{acceptNode(t){const n=t;if(r.length>0&&-1!==r.indexOf(n))return NodeFilter.FILTER_REJECT;if("template"===n.tagName.toLowerCase()){if((n.getAttribute(e.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let a=null;const l=[],c=[];for(;i.nextNode();){const t=i.currentNode;c.push(t)}for(const n of c){let r=n.getAttribute(e.bindAttributeName)||"";"string"==typeof o&&(r=Pr(r,o));let i=At(r)[0];const c=Er.get(i.bindingType);if(void 0===c)continue;const d=i.bindingType,u=n.content,f=Jo();let h=null;const p="for"===d?i.statePathName:o;if("else"===d){null===a&&nt("'else' binding found without preceding 'if' or 'elseif' binding."),i=Tr("else",a.parseBindTextResult),h=Or(t,u,i,p),Rt(f,t,h);const e=l.at(-1),o=document.createComment(`@@${c}:${f}`);void 0!==e?(n.remove(),e.fragment.appendChild(o),e.nodeInfos.push({nodePath:Ar(o),parseBindTextResults:Lt(o)})):n.replaceWith(o)}else if("elseif"===d){null===a&&nt("'elseif' binding found without preceding 'if' or 'elseif' binding."),h=Or(t,u,i,p),Rt(f,t,h);const e=document.createComment(`@@${c}:${f}`),o=Jo(),r={fragment:document.createDocumentFragment(),parseBindTextResult:Tr("else",a.parseBindTextResult),nodeInfos:[]};r.fragment.appendChild(e),r.nodeInfos.push({nodePath:Ar(e),parseBindTextResults:Lt(e)}),Rt(o,t,r);const d=l.at(-1);l.push(r);const m=document.createComment(`@@${s}:${o}`);void 0!==d?(n.remove(),d.fragment.appendChild(m),d.nodeInfos.push({nodePath:Ar(m),parseBindTextResults:Lt(m)})):n.replaceWith(m)}else{h=Or(t,u,i,p),Rt(f,t,h);const e=document.createComment(`@@${c}:${f}`);n.replaceWith(e)}"if"===d?(l.length=0,a=h):"elseif"===d?a=h:"else"===d&&(a=null,l.length=0)}}async function Dr(t){const n=t.querySelectorAll(e.tagNames.state),o=[],s=J(t);null===s&&nt(`CustomElementRegistry is unavailable for <${e.tagNames.state}>.`),await s.whenDefined(e.tagNames.state);for(const t of n){if(jt(t))continue;const e=t;o.push(e.initializePromise)}await Promise.all(o)}async function Lr(t){if(t===document)await Dr(document),br(document),Rr(document,document),mr(document.body,null);else{const n=t;n.host.hasAttribute(e.bindAttributeName)&&await B(n.host),await Dr(n),br(n),Rr(n,n),mr(n,null)}}const jr="1.31.0",Wr="undefined"==typeof HTMLElement?class{}:HTMLElement,Br=/^@@wcs-(?:for|if|elseif|else):[^-]/,Fr=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,zr=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,qr=/^@@wcs-text-start:(.+)$/;function Ur(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class Hr extends Wr{_stateData=null;_templates=null;_hydrateProps=null;get name(){return this.getAttribute("name")||"default"}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=jr.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 findByName(t,n){const o=e.tagNames.ssr,s=t instanceof Element?t:t instanceof Document?t.documentElement:null;if(!s)return null;return s.querySelector(`${o}[name="${n}"]`)}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,n){const o=document.createElement("script");o.setAttribute("type","application/json"),o.textContent=Ur(JSON.stringify(n)),t.appendChild(o);const s=Array.from(Ot.keys());for(const n of s){const o=Dt(n);if(!o)continue;const s=document.createElement("template");s.setAttribute("id",n);const r=o.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(e.bindAttributeName,i);const a=o.fragment.cloneNode(!0);s.content.appendChild(a),t.appendChild(s)}const r=Array.from(Fs);if(r.length>0){const e={};for(let t=0;t<r.length;t++){const n=r[t],o=Bs(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=Ur(JSON.stringify(e)),t.appendChild(n)}}Fs.clear()}static removeBlockBoundaryComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;(Fr.test(t.data)||zr.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;Br.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=qr.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 n=document.body,o=t.querySelectorAll(e.tagNames.ssr),s=new Map;for(const t of o){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(n,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const t=r.currentNode;Fr.test(t.data)&&i.push(t)}for(const t of i){const e=Fr.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()}Hr.restoreTextBindings(n);const a=document.createTreeWalker(n,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const t=a.currentNode;if(Br.test(t.data)){const e=t.data.split(":")[1];l.push({comment:t,uuid:e})}}for(const{comment:t,uuid:n}of l){const o=s.get(n);if(o){const n=document.createElement("template"),s=o.getAttribute(e.bindAttributeName);s&&n.setAttribute(e.bindAttributeName,s);const r=document.importNode(o.content,!0);if(r.childNodes.length>0)n.content.appendChild(r);else for(const t of Array.from(o.childNodes))n.content.appendChild(document.importNode(t,!0));t.parentNode.replaceChild(n,t)}}const c=t.querySelectorAll("[data-wcs-ssr-id]");for(const t of c)t.removeAttribute("data-wcs-ssr-id");for(const t of o)t.remove()}}const Vr=new Set(["for","if","elseif","else"]);function Gr(t){const e=new jo;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]=Ut(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 Kr(t,n,o){const s={for:e.commentForPrefix,if:e.commentIfPrefix,elseif:e.commentElseIfPrefix,else:e.commentElsePrefix}[n];if(!s)return null;const r=`@@${s}:${o}`,i=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const t=i.currentNode;if(t.data===r)return t}return null}function Jr(t,n){const o=t;let s=null;for(const[t,r]of n.templates){let n=At(r.getAttribute(e.bindAttributeName)||"")[0];const i=n.bindingType;"else"===i&&s?n={...s,outFilters:[...s.outFilters,Nr()],bindingType:"else"}:"elseif"===i&&s&&(n={...n,stateName:s.stateName}),"if"===i||"elseif"===i?s=n:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?n.statePathName:void 0;Cr(a),"string"==typeof l&&_r(a,l),Rr(o,a,l);Rt(t,o,{fragment:a,parseBindTextResult:n,nodeInfos:kr(a)})}}async function Xr(t){await Dr(t);const n=t.querySelectorAll(e.tagNames.ssr);for(const e of n){const n=e;if(!n.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${n.version}", client="${jr}". Falling back to full render.`),Hr.cleanupDom(t),!1}for(const e of n)Jr(t,e);const s=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=Fr.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 s of e){if(0===s.nodes.length)continue;const e=_s(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a}=Gr(s.nodes);fs(e,a);for(const t of i)t.nodeType===Node.ELEMENT_NODE&&t.setAttribute("data-wcs-completed","");cs(e,r),ms(e,i);const l=[];for(const t of r)t.statePathName in v&&l.push(t);if(Go(e,l),"for"===s.type&&null!==s.index){const i=Kr(t,"for",s.uuid);if(i){const t=Qo(null,s.index);Os(i,t,e),Rs(i,s.nodes[s.nodes.length-1]),Ns(i,e),gs(e,Le(U(s.path+"."+o),t)),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});let l=n.get(s.uuid);l||(l=[],n.set(s.uuid,l)),l.push(t)}}else{const n=Kr(t,s.type,s.uuid);n&&(Ns(n,e),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}))}}for(const[e,o]of n){const n=Kr(t,"for",e);if(!n)continue;const s=n.getRootNode(),r=Dt(e);if(!r)continue;const i=r.parseBindTextResult.stateName,a=r.parseBindTextResult.statePathName,l=ti(s,i);l&&l.createState("readonly",t=>{const e=t[a];Array.isArray(e)&&es(e,o)})}}(document.body,s),Hr.removeBlockBoundaryComments(document.body);const r=[];for(const t of n)t.parentNode&&(r.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());Hr.restoreTextBindings(document.body);const[i,a]=Ut(document.body);for(const t of i)if(t.nodeType===Node.ELEMENT_NODE){const e=t;e.hasAttribute("data-wcs-completed")||(Jt(t,null),e.setAttribute("data-wcs-completed",""))}else Jt(t,null);const l=[],c=[],d=Wo(document.body).initialize(a);for(const t of d)if("event"!==t.bindingType)if(Vr.has(t.bindingType))c.push(t);else{if(t.statePathName.includes(o))continue;l.push(t)}for(const t of c)if("for"===t.bindingType){const e=$e(t),n=ti(t.replaceNode.getRootNode(),t.stateName);n&&n.createState("readonly",n=>{const o=n[t.statePathName];Array.isArray(o)&&Zt(e,o)})}pr(l);for(const{el:t,parent:e,next:n}of r)e.insertBefore(t,n);const u=t.querySelectorAll(e.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 Yr=new WeakMap,Qr=new WeakMap,Zr=new Set;function ti(t,e){let n=Yr.get(t);return n&&n.get(e)||null}function ei(t){return Qr.get(t)??Promise.resolve()}function ni(e,n,o){let s=Yr.get(e);if(null===o){if(!s)return;const t=s.get(n);s.delete(n),0===s.size&&Yr.delete(e),void 0!==t&&(Zr.delete(t),null!==Xt&&Xt({type:"state:element-unregistered",name:n,rootNode:e,element:t}))}else{if(!s){s=new Map,Yr.set(e,s);const n=!t()&&o.hasAttribute?.("enable-ssr");if("HTMLDocument"===e.constructor.name||"Document"===e.constructor.name){const t=new Promise((t,o)=>{queueMicrotask(async()=>{try{if(n){await Xr(e)||await Lr(e)}else await Lr(e);t()}catch(t){o(t)}})});Qr.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await Lr(e),t()}catch(t){n(t)}})});Qr.set(e,t)}}s.has(n)&&nt(`State element with name "${n}" is already registered.`),s.set(n,o),Zr.add(o),null!==Xt&&Xt({type:"state:element-registered",name:n,rootNode:e,element:o})}}let oi=0,si=0;const ri=[];function ii(t,e=0){const n=ri.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?ri.push(o):ri.splice(n,0,o)}const ai=new class{_queueUpdateRecords=[];constructor(){}enqueueAbsoluteAddress(t,e=null){oi>si&&(si=oi);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 e=new Map;for(const n of t){const t=e.get(n.absoluteAddress);null!==Xt&&null!=t&&null!==n.context&&t.transactionId!==n.context.transactionId&&Xt({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:t.transactionId,winnerTransactionId:n.context.transactionId}),e.set(n.absoluteAddress,n.context)}const n=[],o=new Map;for(const[t,s]of e){if(null!==s&&s.hop>=32){console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:t.absolutePathInfo.pathInfo.path,stateName:t.absolutePathInfo.stateName,transactionId:s.transactionId,hop:s.hop,maxHops:32}),null!==Xt&&Xt({type:"propagation:hop-limit",absoluteAddress:t,transactionId:s.transactionId,hop:s.hop});continue}const e=Te(t);if(void 0!==e)if(e instanceof Set)for(const t of e)!1!==t.replaceNode.isConnected&&(n.push(t),null!==s&&o.set(t,s));else!1!==e.replaceNode.isConnected&&(n.push(e),null!==s&&o.set(e,s))}try{o.size>0?pr(n,o):pr(n)}finally{!function(t){for(const e of ri.slice())e.listener(t)}(new Set(e.keys()))}}};function li(){return ai}const ci=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function di(t,e,n,o){return{node:t,propName:e.propName,statePathName:e.statePathName,stateName:e.stateName,bindingType:e.bindingType,inFilters:e.inFilters,outFilters:e.outFilters,origin:n,raw:o}}const ui="__WCSTACK_DEVTOOLS_HOOK__";function fi(){const t=globalThis,e=t[ui];if(void 0!==e)return 1!==e.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${e.version}, expected 1. 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:1,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[ui]=n,n}const hi=t=>{null!==Xt&&Xt({type:"state:update-batch",addresses:t})};function pi(t){const e=null!==Xt;!function(t){Xt=t}(t);const n=null!==t;n&&!e?ii(hi,0):!n&&e&&function(t){const e=ri.findIndex(e=>e.listener===t);-1!==e&&ri.splice(e,1)}(hi)}function mi(t){return{name:t.name,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 gi(t,e){return ti(e,t)??nt(`devtools: state element not found: name="${t}"`)}let yi=null;function bi(){if(t())return;if(null!==yi)return;const n={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:jr,getStateElements(){const t=[];for(const e of Zr)t.push(mi(e));return t},keys(t,e){const n=gi(t,e),o=[];return n.createState("readonly",t=>{for(const e of Object.keys(t))if(!e.includes("*")&&!e.startsWith("$")){try{if("function"==typeof t[e])continue}catch{}o.push(e)}}),o},read(t,e,n,o){let s;return gi(t,e).createState("readonly",t=>{s=t.$resolve(n,o??[])}),s},write(t,e,n,o,s){gi(t,e).createState("writable",t=>{void 0!==s&&s.length>0?t.$resolve(n,s,o):t[n]=o})},getDeclaredBindings:t=>function(t){const n=[],o=new Set,s=new Set,r=t=>{const e=function(t){const e=[...t.inFilters,...t.outFilters].map(t=>`${t.filterName}(${t.args.join(",")})`).join("|");return[t.stateName,t.statePathName,t.propName,t.bindingType,e].join("\0")}(t);o.has(e)||(o.add(e),n.push(t))},i=t=>{if(s.has(t))return;s.add(t);const e=Dt(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(di(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 n=t,o=n.getAttribute(e.bindAttributeName);if(null===o||0===o.length)continue;try{const t=rt(n,At(o));for(const e of t)r(di(n,e,"attribute",o))}catch{}continue}const n=ci.exec(t.data.trim());if(null===n)continue;const o=n[1]||e.commentTextPrefix,s=n[2],a=Dt(s);if(null===a){if(o===e.commentTextPrefix)try{r(di(t,Tt(s),"comment",s))}catch{}}else r(di(t,a.parseBindTextResult,"comment",s)),i(s)}return n}(t),_setSink:pi};yi=n,fi().register(n)}const wi="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";async function vi(t,e){let n=null;const o=`\n//# sourceURL=${e}\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 ${wi}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${wi}`}(e,t,s),{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function Ni(t){try{return(await import(t)).default||{}}catch(t){nt(`Failed to load script file: ${t}`)}}class Si{_loopContextStack=Array(s).fill(void 0);_length=0;_getBaseDepth;constructor(t){this._getBaseDepth=t}createLoopContext(t,e){null===t.listIndex&&nt("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=s&&nt("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&&nt("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&&nt("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else if(n.listIndex.length!==n.pathInfo.wildcardCount){const t=this._getBaseDepth();n.listIndex.length!==n.pathInfo.wildcardCount+t&&nt(`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}, base depth ${t}).`)}let r;this._loopContextStack[this._length]=n,this._length++;try{r=e(n)}finally{r instanceof Promise?r.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return r}}const Ii=new WeakMap;function xi(t,e){let n=Ii.get(t);void 0===n&&(n=new Map,Ii.set(t,n));let o=n.get(e);return void 0===o&&(o=new nn(e,t.name),n.set(e,o)),o}const $i=new WeakMap;function Pi(t){const e=$i.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 xi(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:xi(t,n)}},set(){nt("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){nt("$command namespace is read-only; deleting from it is not allowed.")}});return $i.set(t,n),n}const _i=Symbol("wcs-stream-last-notified-uncertain"),Ai=new WeakMap;function ki(t,e){const n=Ai.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function Ci(t,e){const n=Ai.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:_i,error:Object.is(o.error,null)?null:_i})}const Ei=new Set;function Mi(t){Ei.delete(t)}const Ti=new WeakMap;function Oi(t){return Ti.get(t)??new Map}function Ri(t){Mi(t);const e=Ti.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Ci(t,n.name)}const Di=(t,e)=>e,Li=new Set;function ji(t,e){const s=e[E];if(void 0===s)return void ki(t,Li);"object"==typeof s&&null!==s||nt(`${E} must be an object mapping stream names to stream definitions.`);const r=new Map;for(const[i,a]of Object.entries(s)){0===i.length&&nt(`${E} entry name must be a non-empty string.`),i.includes(n)&&nt(`${E} entry "${i}" must be a flat property name ("${n}" is not allowed).`),i.includes(o)&&nt(`${E} entry "${i}" must be a flat property name ("${o}" is not allowed).`),i.startsWith("$")&&nt(`${E} entry "${i}" must not start with "$" (reserved namespace).`),i in Object.prototype&&nt(`${E} entry "${i}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(i)&&nt(`${E} entry "${i}" conflicts with a getter declared on the state.`),t.setterPaths.has(i)&&nt(`${E} entry "${i}" conflicts with a setter declared on the state.`),"object"==typeof a&&null!==a||nt(`${E} entry "${i}" must be an object ({ args?, source, fold?, initial? }).`);const s=a;"function"!=typeof s.source&&nt(`${E} entry "${i}" source must be a function.`);const l=void 0!==s.fold;l&&"function"!=typeof s.fold&&nt(`${E} entry "${i}" fold must be a function.`),l&&!("initial"in s)&&nt(`${E} entry "${i}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==s.args&&"function"!=typeof s.args&&nt(`${E} entry "${i}" args must be a function.`);const c={name:i,definition:{args:s.args??null,source:s.source,fold:s.fold??Di,initial:s.initial},status:"idle",error:null,controller:null,depAddresses:new Set};i in e||(e[i]=c.definition.initial),r.set(i,c)}!function(t,e){Ti.set(t,e)}(t,r),ki(t,new Set(r.keys()))}const Wi=new WeakMap,Bi=new WeakMap;function Fi(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=Oi(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&Oi(t).has(n),ownKeys:()=>Array.from(Oi(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=Oi(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){nt(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){nt(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function zi(t){const e=Wi.get(t);if(void 0!==e)return e;const n=Fi(t,O,t=>t.status);return Wi.set(t,n),n}function qi(t){const e=Bi.get(t);if(void 0!==e)return e;const n=Fi(t,R,t=>t.error);return Bi.set(t,n),n}function Ui(t){Wi.delete(t),Bi.delete(t)}let Hi=null;async function Vi(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 Gi(t){const e=Oi(t);if(0!==e.size){!function(t){Ei.add(t)}(t);for(const n of e.values())Ki(t,n)}}function Ki(t,e){e.controller?.abort();const o=new AbortController;e.controller=o;const s=function(t,e){const o=e.definition.args;if(null===o)return void e.depAddresses.clear();const s=Hi,r=new Set;let i;Hi=r;try{t.createState("readonly",t=>{i=o(t)})}finally{Hi=s}i instanceof Promise&&nt(`${E} entry "${e.name}" args must be synchronous (it returned a Promise).`);const a=`${O}${n}${e.name}`,l=`${R}${n}${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||nt(`${E} 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&&nt(`${E} 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}),Ji(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(){Ji(t,e,"done",null)},fail(n){Ji(t,e,"error",n),o.abort()}};Vi(r.source,s,o.signal,i)}function Ji(t,e,o,s){e.status=o,e.error=s;const r=function(t,e){return Ai.get(t)?.get(e)??{status:"idle",error:null}}(t,e.name),i=r.status!==o,a=!Object.is(r.error,s);(i||a)&&(!function(t,e,n,o){let s=Ai.get(t);void 0===s&&(s=new Map,Ai.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,o,s),t.createState("writable",t=>{i&&t.$postUpdate(`${O}${n}${e.name}`),a&&t.$postUpdate(`${R}${n}${e.name}`)}))}ii(function(t){const e=Ei;if(0===e.size)return;const n=[];for(const o of e)for(const e of Oi(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)&&Oi(t).get(o.name)===o)try{Ki(t,o)}catch(n){o.controller?.abort(),e.has(t)&&Oi(t).get(o.name)===o&&Ji(t,o,"error",n)}},20);const Xi=new WeakMap,Yi=new Set,Qi=new Map;function Zi(t){return Xi.get(t)??Qi}function ta(){return Yi}function ea(t,e){const n=e[M];if(void 0===n)return null;"object"==typeof n&&null!==n||nt(`[wcs/watch-declaration-invalid] ${M} must be an object mapping state paths to handler functions.${dt}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&nt(`[wcs/watch-declaration-invalid] ${M} entry "${e}" must be a function.${dt}`),0===e.length&&nt(`[wcs/watch-declaration-invalid] ${M} entry name must be a non-empty state path.`),e.startsWith("$")&&nt(`[wcs/watch-declaration-invalid] ${M} entry "${e}" must not start with "$" (reserved namespace).${dt}`),e.includes("@")&&nt(`[wcs/watch-declaration-invalid] ${M} entry "${e}" must not target another state ("@" is not allowed); watch only paths of its own state.${dt}`),e in Object.prototype&&nt(`[wcs/watch-declaration-invalid] ${M} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const n=U(e);for(const t of n.segments)0===t.length&&nt(`[wcs/watch-declaration-invalid] ${M} entry "${e}" has an empty path segment.${dt}`);n.wildcardCount>128&&nt(`[wcs/watch-declaration-invalid] ${M} entry "${e}" exceeds the maximum wildcard depth (128).`),o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){Xi.set(t,e)}(t,o),s.size>0?s:null}const na=new WeakMap;function oa(t,e,n){let o=na.get(t);void 0===o&&(o=new Map,na.set(t,o)),o.set(e,n)}const sa=new Map;function ra(t){0!==Zi(t).size&&(function(t){Yi.add(t)}(t),function(t){const e=[];for(const n of Zi(t).values())aa(t,n)&&e.push(n);if(0===e.length)return;t.createState("readonly",n=>{for(const o of e)try{oa(t,ia(t,o),n[o.path])}catch(e){ca(t,o.path,"prime",e)}})}(t))}function ia(t,e){return he(le(t,e.pathInfo),null)}function aa(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const la={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function ca(t,e,n,o){console.error(`[@wcstack/state] $watch ${la[n]} "${e}" threw.`,o),null!==Xt&&Xt({type:"state:watch-error",phase:n,stateName:t.name,path:e,error:o})}function da(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 ua(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=aa(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 ca(e,n.path,"evaluate",t)}const a=r?function(t,e){return na.get(t)?.get(e)}(e,o):function(t){return sa.get(t)}(o);r&&oa(e,o,i),null!==Xt&&Xt({type:"state:watch-fired",stateName:e.name,path:n.path}),n.handler.call(t,i,a,...s)})}catch(t){ca(e,n.path,"handler",t)}}function fa(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 ha(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 pa(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 ma(t){return t.startsWith("$")}function ga(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 ya(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 ba(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||nt(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||nt(`${e} entries must be non-empty strings.`),t.startsWith("$")&&nt(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&nt(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}function wa(t){const e=ba(t,$)??[],n=ba(t,P)??[],o=ga(t),s=function(t){const e=t[E];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}nt(`${$} entry "${t}" is not declared on the state.${ct(t,ya(o,"value"))}`)}"function"==typeof e.value&&nt(`${$} entry "${t}" is a method. Declare it in ${P} instead.`)}for(const t of n){const e=o[t];void 0===e&&nt(`${P} entry "${t}" is not declared on the state.${ct(t,ya(o,"method"))}`),"function"!=typeof e.value&&nt(`${P} entry "${t}" is not a method. Declare it in ${$} instead.`)}return{bindables:e,commands:n,streamBackedBindables:r}}ii(function(t){const e=ta();try{if(0===e.size)return;const n=function(){const t=si;return si=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!==Xt&&Xt({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=Zi(t).get(n.absolutePathInfo.pathInfo.path);if(void 0===s)continue;let r=[];if(s.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;r=ve(n.listIndex,s.pathInfo.wildcardCount)}o.push({stateElement:t,entry:s,absAddress:n,indexes:r})}if(0===o.length)return;o.sort(da),function(t){oi=t+1}(n);try{for(const t of o)e.has(t.stateElement)&&Zi(t.stateElement).get(t.entry.path)===t.entry&&ua(t)}finally{oi=0}}finally{sa.clear()}},10);const va=new Map;class Na{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=U(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 Sa(t){let e;return va.get(t)??(va.set(t,e=new Na(t)),e)}const Ia=new WeakMap;function xa(t,e){null===e?Ia.delete(t):Ia.set(t,e)}function $a(t){const e=Ia.get(t);e&&(e.dirty=!0)}const Pa=[],_a=[];let Aa=0;function ka(t,e){Pa[Aa]=t,_a[Aa]=e,Aa++}function Ca(){Aa--,Pa[Aa]=void 0,_a[Aa]=void 0}function Ea(t,e){return!0!==t.hasMappedComponentState&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function Ma(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 Ta(t,e,n,s,r){const i=e.pathInfo.segments[0];if(i===A)return Ma(Pi(r),e.pathInfo.segments);if(i===O)return Ma(zi(r),e.pathInfo.segments);if(i===R)return Ma(qi(r),e.pathInfo.segments);if(!(e.pathInfo.path in t)){const i=e.parentAddress??nt(function(t,e,n,o){return`[${Xs.binding}] Path "${e}" does not exist on state "${t}".${ct(e,Js(n,"",o))}${dt}`}(r.name,e.pathInfo.path,t,r.getterPaths)),a=Ra(t,i,n,s);if(null==a)return;const l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(l===o){const t=e.listIndex?.index??nt(Zs(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.get(a,t)}return Reflect.get(a,l)}if(r.getterPaths.has(e.pathInfo.path)){s.pushAddress(e);try{return Reflect.get(t,e.pathInfo.path,n)}finally{s.popAddress()}}else{if(!0!==r.hasMappedComponentState)return Reflect.get(t,e.pathInfo.path);ka(r,e);try{return Reflect.get(t,e.pathInfo.path)}finally{Ca()}}}function Oa(t,e,n,o,s){const r=he(le(s,e.pathInfo),e.listIndex),i=function(t){return Ia.get(t)??null}(r);if(null!==i&&!1===i.dirty)return i.value;const a=Ta(t,e,n,o,s);return xa(r,{value:a,dirty:!1}),a}function Ra(t,e,n,o){!function(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=be(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?we(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?we(a,n,o.wildcardCount):null)){r=!0;break}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}(o,e),function(t,e){if(null===Hi)return;const n=le(t,e.pathInfo);Hi.add(he(n,e.listIndex))}(o.stateElement,e);const s=o.stateElement;return Ea(s,e)?Oa(t,e,n,o,s):Ta(t,e,n,o,s)}function Da(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:we(n.listIndex,o,n.pathInfo.wildcardCount)}function La(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 ja(t,e,n,o){"object"==typeof t&&null!==t||nt(`${T} 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&&nt(`${T} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function Wa(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&nt(`${T} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function Ba(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];ja(a,n,o,i);const l=Wa(a,e,n,o,i);r.has(l)&&nt(`${T} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Fa(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 za(t,e,n,s){if(e.pathInfo.path in t)return!0;const r=e.parentAddress;if(null===r)return!1;const i=Ra(t,r,n,s);if(null===i||"object"!=typeof i&&"function"!=typeof i)return!1;const a=e.pathInfo.lastSegment;if(a===o){const t=e.listIndex?.index;return"number"==typeof t&&t in i}return a in i}const qa=new WeakMap;function Ua(t,e){null===e?qa.delete(t):qa.set(t,e)}function Ha(t,e,n){const o=U(t.wildcardParentPaths[e]),s=le(t.stateElement,o),r=Le(o,n),i=Qt(he(s,n)),a=t.stateProxy[ee](r),l=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[]}}(rs(Jn(t.stateElement,r.listIndex),i,a),t.searchType);if(e===t.wildcardPaths.length-1)t.targetListIndexes.push(...l);else for(const n of l)Ha(t,e+1,n)}const Va=[];function Ga(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:Va,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:Va,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Ka=[];function Ja(t,e,o){const s=t.stateElement.indexDependentGetterPaths;if(!s||0===s.size)return Ka;let r=null;const i=e+n;for(const t of s){if(t!==e&&!t.startsWith(i))continue;const n=U(t);if(n.wildcardCount!==o.wildcardCount)return null;(r??=[]).push(n)}return r??Ka}function Xa(t,e,n){const s=e.pathInfo.path,r=t.staticMap.get(s);if(r)for(const i of r){const r=U(i);if(t.listPathSet.has(s)&&r.lastSegment===o){const o=t.stateProxy[ee](e),a=Qt(he(le(t.stateElement,e.pathInfo),e.listIndex)),l=Ga(t,s,0,0,rs(Jn(t.stateElement,e.listIndex),a,o));for(const e of l.fullRows){const o=Le(r,e);t.result.add(o),n.push(o)}if(null!==l.movedRows){const e=Ja(t,i,r);if(null===e)for(const e of l.movedRows){const o=Le(r,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=Le(s,o);t.result.add(e),n.push(e)}}}else{const o=Le(r,e.listIndex);t.result.add(o),n.push(o)}}const i=t.dynamicMap.get(s);if(i)for(const o of i){const s=U(o),r=[];if(s.wildcardCount>0){const n=be(e.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&nt(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=we(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const i={stateName:t.stateName,stateElement:t.stateElement,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};Ha(i,n,o),r.push(...i.targetListIndexes)}else{null===e.listIndex&&nt(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=we(e.listIndex,n-1,e.pathInfo.wildcardCount);r.push(t)}}else r.push(null);for(const e of r){const o=Le(s,e);t.result.add(o),n.push(o)}}}function Ya(t,e,n,o,s,r,i,a,l,c){const d=n.pathInfo.path;if(!o.has(d)&&!s.has(d))return l(n),[];const u=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&&nt(`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}(d,o,s,1e3),f={ranks:u,stateName:t,stateElement:e,staticMap:o,dynamicMap:s,result:new Set,listPathSet:r,visited:new Set,stateProxy:i,searchType:a,listExpansion:c?.listExpansion??"full",keyedMergePath:c?.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,Xa(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}(f,n,l),Array.from(f.result)}function Qa(t,e,n,o,s){const r=t.watchPaths;null!=r&&s&&r.has(e)&&function(t,e){sa.has(t)||sa.set(t,e)}(n,o)}function Za(t,e,n,o,s){const r=An()??$n(-1),i=li();i.enqueueAbsoluteAddress(e,r),Ya(o.stateName,o.stateElement,t,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{if(e===t)return;const n=he(le(o.stateElement,e.pathInfo),e.listIndex);$a(n),i.enqueueAbsoluteAddress(n,r)},{listExpansion:"diff",keyedMergePath:s})}function tl(t,e,n,s,r,i,a){try{if(!(e.pathInfo.path in t)){const n=e.parentAddress;if(null===n)return Reflect.set(t,e.pathInfo.path,s);const a=Ra(t,n,r,i),l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(l===o){const t=e.listIndex?.index??nt(Zs(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.set(a,t,s)}return Reflect.set(a,l,s)}if(i.stateElement.setterPaths.has(e.pathInfo.path)){i.pushAddress(e),i.beginUntrack();try{return Reflect.set(t,e.pathInfo.path,s,r)}finally{i.endUntrack(),i.popAddress()}}else{if(!0!==i.stateElement.hasMappedComponentState)return Reflect.set(t,e.pathInfo.path,s);ka(i.stateElement,e);try{return Reflect.set(t,e.pathInfo.path,s)}finally{Ca()}}}finally{Za(e,n,r,i,a)}}function el(t,e,n,o,s,r,i){let a=e.parentAddress??nt(`address.parentAddress is undefined path: ${e.pathInfo.path}`),l=function(t){return qa.get(t)??null}(a);if(null===l){const e=Ra(t,a,s,r)??[],n=ts(e)??[];l={value:[...e],listIndexes:[...n]},Ua(a,l)}try{return tl(t,e,n,o,s,r,i)}finally{const n=l.value.indexOf(o),i=Ra(t,a,s,r)??[],c=Array.isArray(i)?ts(i)??[]:[],d=e.listIndex.index,u=-1!==n?l.listIndexes[n]:Qo(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;Ua(a,null)}}}function nl(t,e,s,r,i){const a=i.stateElement.listKeys;if(null!=a&&Array.isArray(s)){const l=a.get(e.pathInfo.path);if(void 0!==l){const a=Ra(t,e,r,i),c=function(t,e,n,o){const s=Ba(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Ba(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,s);if(null!==c)return function(t,e,s,r,i,a){const l=e.pathInfo.path,c=Jn(a.stateElement,e.listIndex);null===ts(r)&&rs(c,null,r);const d=rs(c,r,s.list),u=ol(t,e,s.list,i,a,l),f=U(l+n+o);for(const e of s.matched){const o=Fa(e.oldRow,e.newRow);if(0===o.length)continue;const s=d.newIndexes[e.position];for(const r of o)void 0!==s?nl(t,Le(U(f.path+n+r.field),s),r.value,i,a):e.oldRow[r.field]=r.value}return u}(t,e,c,a,r,i)}}return ol(t,e,s,r,i,null)}function ol(t,n,s,r,i,a){const l=i.stateElement,c=n.pathInfo.path,d=!!En&&(En=!1,!0);if(!(c in t)&&null!==n.parentAddress&&!l.elementPaths.has(c)){const u=Ra(t,n.parentAddress,r,i);if("object"==typeof u&&null!==u){const t=n.pathInfo.lastSegment,f=t===o?n.listIndex?.index:t;let h,p=!1;if(!d&&e.sameValueGuard&&(null===s||"object"!=typeof s)){const t=void 0!==f&&f in u,e=void 0!==f?u[f]:void 0;if(t&&Object.is(e,s))return!0;h=e,p=!0}const m=Ea(l,n),g=he(le(l,n.pathInfo),n.listIndex);null!==Xt&&Xt({type:"state:write",absoluteAddress:g,value:s,oldValue:h,hasOldValue:p}),Qa(l,c,g,h,p);try{return void 0===f&&nt(Zs(`path "${c}"`,n.pathInfo.wildcardCount,n.listIndex?.length??0)),Reflect.set(u,f,s)}finally{Za(n,g,r,i,a),m&&xa(g,{value:s,dirty:!1}),La(l,n.pathInfo,{value:s})}}}let u,f=!1;if(!d&&e.sameValueGuard&&(null===s||"object"!=typeof s)){const e=Ra(t,n,r,i);if(za(t,n,r,i)&&Object.is(e,s))return!0;u=e,f=!0}const h=l.elementPaths.has(n.pathInfo.path),p=Ea(l,n),m=he(le(l,n.pathInfo),n.listIndex);null!==Xt&&Xt({type:"state:write",absoluteAddress:m,value:s,oldValue:u,hasOldValue:f}),Qa(l,c,m,u,f);try{return h?el(t,n,m,s,r,i,a):tl(t,n,m,s,r,i,a)}finally{p&&xa(m,{value:s,dirty:!1}),La(l,n.pathInfo,{value:s})}}function sl(t,e,n,o){return(e,s,r)=>{const i=U(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&&nt(Qs("$resolve",e,i.wildcardParentPathInfos.length,s.length));let a=null;for(let e=0;e<i.wildcardParentPathInfos.length;e++){const r=i.wildcardParentPathInfos[e],l=Le(r,a),c=ts(Ra(t,l,n,o));null==c&&nt(`ListIndexes not found: ${r.path}`);const d=s[e];a=c[d]??nt(`ListIndex not found at index ${d} of ${r.path}`)}const l=Le(i,a);if(!(void 0!==r))return Ra(t,l,n,o);nl(t,l,r,n,o)}}const rl=new WeakMap;function il(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return Da(o,s.wildcardPaths.at(-1)??nt(`lastWildcardPath is null: ${e.pathInfo.path}`))??nt(`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]??nt(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=ts(Ra(t,Le(i,s),n,o))??nt(`ListIndex not found: ${i.path}`),l=e.wildcardIndexes[r]??nt(`wildcardIndex is null: ${e.pathInfo.path}`);s=a[l]??nt(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":nt(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}const al=`${O}${n}`,ll=`${R}${n}`,cl=new WeakMap;function dl(t,e,n,o){const s=v[e];if(void 0!==s){0===o.addressStackLength&&nt(`No active state reference to get list index for "${e.toString()}".`);const t=o.lastAddressStack,n=t?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const r=t?.listIndex;null==r&&nt(`ListIndex not found: ${e.toString()}`);const i=we(r,s,t.pathInfo.wildcardCount);return i?.index??nt(`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=sl(t,0,n,o);return(e,r)=>{const i=new Map,a=U(e);if(o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==a.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(a.path,t.path)}if(void 0!==r&&r.length>a.wildcardParentPathInfos.length&&nt(Qs("$getAll",e,a.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=0;t<a.wildcardParentPathInfos.length;t++){const e=a.wildcardParentPathInfos[t],n=Da(o,e.path);if(n){r=ve(n,n.length-Gn(o.stateElement));break}}void 0===r&&(r=[])}const l=(e,s,r,a,c,d,u)=>{const f=e[s]??null;if(null===f)return void u.push(d);const h=Le(f,r),p=rl.get(h),m=Ra(t,h,n,o),g=rs(Jn(o.stateElement,r),p,m).newIndexes,y=a[c]??null;if(i.set(h,m),null===y)for(let t=0;t<g.length;t++){const n=g[t];l(e,s+1,n,a,c+1,d.concat(n.index),u)}else{const t=g[y]??nt(`ListIndex not found at index ${y} of ${f.path}`);s+1<e.length?l(e,s+1,t,a,c+1,d.concat(t.index),u):u.push(d.concat(t.index))}},c=[];l(a.wildcardParentPathInfos,0,null,r,0,[],c);const d=[];for(let t=0;t<c.length;t++)d.push(s(a.path,c[t]));for(const[t,e]of i.entries())rl.set(t,e);return d}}(t,0,n,o)(e,s);case"$postUpdate":return e=>function(t,e,n,o){const s=o.stateElement;return e=>{const r=Sa(e),i=il(t,r,n,o),a=Le(r.pathInfo,i),l=he(le(s,a.pathInfo),a.listIndex),c=li();c.enqueueAbsoluteAddress(l),Ya(o.stateName,o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=he(le(s,t.pathInfo),t.listIndex);$a(e),c.enqueueAbsoluteAddress(e)}),La(s,a.pathInfo)}}(t,0,n,o)(e);case"$resolve":return(e,s,r)=>sl(t,0,n,o)(e,s,r);case"$trackDependency":return t=>function(t,e,n,o){return t=>{0===o.addressStackLength&&nt(`No active state reference to track dependency for path "${t}".`);const e=o.lastAddressStack?.pathInfo??nt("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 A:return Pi(o.stateElement);case O:return zi(o.stateElement);case R:return qi(o.stateElement)}if(!e.startsWith(al)&&!e.startsWith(ll))return}const s=Sa(e),r=il(t,s,n,o),i=Le(s.pathInfo,r);return Ra(t,i,n,o)}if("symbol"==typeof e){const s=function(t){let e=cl.get(t);return void 0===e&&(e=new Map,cl.set(t,e)),e}(o),r=s.get(e);if(void 0!==r)return r;let i;switch(e){case te:i=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&nt("already in loop context"),t.setLoopContext(e);try{t.pushAddress(e);try{return n()}finally{t.popAddress()}}finally{t.clearLoopContext()}}(o,t,e);break;case ee:i=e=>Ra(t,e,n,o);break;case ne:i=e=>za(t,e,n,o);break;case oe:i=(e,s)=>nl(t,e,s,n,o);break;case se:i=()=>async function(t,e,n){const o=Reflect.get(t,N);"function"==typeof o&&await o.call(n)}(t,0,n);break;case re:i=()=>function(t,e,n){const o=Reflect.get(t,S);"function"==typeof o&&o.call(n)}(t,0,n);break;case ie:i=e=>function(t,e,n,o){const s=Reflect.get(t,I);if("function"==typeof s){const t=new Set,r={};for(const n of e){const e=n.absolutePathInfo.pathInfo;let s;if(s=n.absolutePathInfo.stateName===o.stateName?e.path:e.path+"@"+n.absolutePathInfo.stateName,t.add(s),e.wildcardCount>0){const t=ve(n.listIndex,e.wildcardCount),o=r[s];void 0===o?r[s]=[t]:o.push(t)}}return s.call(n,Array.from(t),r)}}(t,e,n,o);break;default:return Reflect.get(t,e,n)}return s.set(e,i),i}}class ul{_stateElement;_stateName;_addressStack=Array(s).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e,n){this._stateName=e;const o=ti(t,this._stateName);null===o&&nt(`StateHandler: State element with name "${this._stateName}" not found.`),this._stateElement=o,this._mutability=n}get stateName(){return this._stateName}get stateElement(){return this._stateElement}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&nt("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=s&&nt(`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&&nt(`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 dl(t,e,n,this)}set(t,e,n,o){return"readonly"===this._mutability&&nt(`State "${this._stateName}" is readonly.`),function(t,e,n,o,s){if("string"==typeof e){const r=Sa(e),i=il(t,r,o,s);return nl(t,Le(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 fl(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)}class hl{_webComponent;_innerStateElement;constructor(t,e){this._webComponent=t,this._innerStateElement=zn(t,e)??nt("State element not found for web component.")}_outerLoopContext(t,e){const n=e.pathInfo.wildcardCount,o=Kn(e.stateElement,e.pathInfo),s=Kt(this._webComponent);if(null!==s&&s.listIndex.length===o)return s;if(n>0){const s=function(t,e){if(0===Aa)return null;const n=Aa-1,o=_a[n];return Pa[n]!==t||o?.pathInfo.path!==e?null:o}(this._innerStateElement,t.path),r=s?.listIndex??null;if(null!==r&&r.length===o){return Le(U(e.pathInfo.wildcardPaths[n-1]),r)}}return s}get(t,e,n){if("string"!=typeof e)return Reflect.get(t,e,n);{if("then"===e)return;if("$"===e[0])return;if(this._innerStateElement.getterPaths.has(e)&&e in t)return Reflect.get(t,e,n);const o=U(e),s=le(this._innerStateElement,o),r=eo(this._webComponent,s);if(null!==r){const t=this._outerLoopContext(o,r);let e;return r.stateElement.createState("readonly",n=>{n[te](t,()=>{e=n[r.pathInfo.path]})}),e}if(e in t)return Reflect.get(t,e,n);nt(`Property "${e}" not found in inner state: no mapping rule and no local state property.`)}}set(t,e,n,o){if("string"!=typeof e)return Reflect.set(t,e,n,o);{if(this._innerStateElement.setterPaths.has(e)&&e in t)return Reflect.set(t,e,n,o);const s=U(e),r=le(this._innerStateElement,s),i=eo(this._webComponent,r);if(null!==i){const t=this._outerLoopContext(s,i);return i.stateElement.createState("writable",e=>{e[te](t,()=>{e[i.pathInfo.path]=n})}),!0}if(e in t)return Reflect.set(t,e,n,o);nt(`Property "${e}" not found in inner state: no mapping rule and no local state property.`)}}has(t,e){if("string"==typeof e){if("$"===e[0])return!1;if((this._innerStateElement.getterPaths.has(e)||this._innerStateElement.setterPaths.has(e))&&e in t)return!0;const n=U(e),o=le(this._innerStateElement,n);return null!==eo(this._webComponent,o)||e in t}return Reflect.has(t,e)}}class pl{_innerStateElement;constructor(t,e){this._innerStateElement=zn(t,e)??nt("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 ml=t=>()=>t;function gl(t,n,o,s){!function(t,e,n){let o=Fn.get(t);o||(o=new Map,Fn.set(t,o)),o.set(e,n)}(n,o,t);const r=n.hasAttribute(e.bindAttributeName)?(i=n,(at.get(i)||null)??[]).filter(t=>t.propSegments[0]===o):[];var i;r.length>0?(!function(t,e,n){if(0===n.length)return;const o=zn(t,e);null===o&&nt("State element not found for web component.");const s=new Map,r=new Map;for(const e of n){const n=to(o,e);let i=Qn.get(t);void 0===i?Qn.set(t,new Set([n])):i.add(n);const a=n.innerAbsPathInfo,l=n.outerAbsPathInfo;Zn.set(n,e),s.set(a,l),r.set(l,a),Un(t,l.stateElement)}Xn.set(t,s),Yn.set(t,r)}(n,o,r),t.markComponentStateMapped?.(),t.setInitialState(function(t,e){const n=new hl(t,e),o=zn(t,e);null===o&&nt("State element not found for web component."),null===o.boundComponentStateProp&&nt("State element is not bound to any component state prop."),o.boundComponentStateProp in t||nt(`State element is not bound to a valid component state prop: ${o.boundComponentStateProp}`);const s=t[o.boundComponentStateProp];return"object"==typeof s&&null!==s||nt(`Invalid state object for component state prop: ${o.boundComponentStateProp}`),new Proxy(fl(s),n)}(n,o))):t.setInitialState(fl(s));const a=function(t,e){const n=new pl(t,e);return new Proxy({},n)}(n,o);if(Object.defineProperty(n,o,{get:ml(a),enumerable:!0,configurable:!0}),function(t,e){let n=Fo.get(t);n||(n=new Set,Fo.set(t,n)),n.add(e)}(n,o),x in n){const t=n[x];"function"==typeof t?t.call(n,o).catch(t=>{nt(`Error in ${x}: ${t instanceof Error?t.message:String(t)}`)}):nt(`${x} is not a function.`)}}class yl extends Wr{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return ei(t)}__state;_hasUpdatedCallback=!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(t=()=>0){return new Si(t)}(()=>Gn(this));_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_watchPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMappedComponentState=!1;_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&&nt(`${e.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){this._commandTokenNames=function(t){const e=new Set,n=t[_];if(void 0===n)return e;Array.isArray(n)||nt(`${_} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||nt(`${_} entries must be non-empty strings.`),t===A&&nt(`${_} entry "${t}" conflicts with the reserved namespace name "${A}".`),e.has(t)&&nt(`${_} entry "${t}" is duplicated.`),e.add(t);return e}(e),this._eventTokenNames=function(t){const e=new Set,n=t[k];if(void 0===n)return e;Array.isArray(n)||nt(`${k} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||nt(`${k} entries must be non-empty strings.`),e.has(t)&&nt(`${k} entry "${t}" is duplicated.`),e.add(t);return e}(e),this.__state=e,this._hasUpdatedCallback=I in e,Ze(this),function(t,e,n){const o=e[C];if(void 0!==o){"object"==typeof o&&null!==o||nt(`${C} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||nt(`${C} entry "${e}" is not declared in $eventTokens.${ct(e,n)}`),"function"!=typeof s&&nt(`${C} entry "${e}" must be a function.`),Qe(t,e).subscribe(s)}}(this,e,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const s=function(t){const e=new Set,n=new Set,o=ga(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}}(e);for(const t of s.getterPaths)this._getterPaths.add(t);for(const t of s.setterPaths)this._setterPaths.add(t);var r;Ui(this),Ri(r=this),Mi(r),Ti.delete(r),ji(this,e),this._listKeys=function(t){const e=t[T];if(void 0===e)return null;"object"==typeof e&&null!==e||nt(`${T} must be an object mapping list paths to key specs.`);const s=new Map;for(const[t,r]of Object.entries(e)){0===t.length&&nt(`${T} entry path must be a non-empty string.`);const e=t.split(n);e.some(t=>0===t.length)&&nt(`${T} entry "${t}" must not contain empty path segments.`),e[e.length-1]===o&&nt(`${T} entry "${t}" must be the list path itself, not the element path (drop the trailing "${n}${o}").`),"function"!=typeof r?("string"!=typeof r&&nt(`${T} entry "${t}" key spec must be a field name (string) or a function.`),0===r.length&&nt(`${T} entry "${t}" key field name must be a non-empty string.`),(r.includes(n)||r.includes(o))&&nt(`${T} entry "${t}" key field name "${r}" must be a flat property name ("${n}" / "${o}" are not allowed).`),r in Object.prototype&&nt(`${T} entry "${t}" key field name "${r}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),s.set(t,r)):s.set(t,r)}return s.size>0?s:null}(e),function(t){Yi.delete(t),Xi.delete(t)}(this),function(t){na.delete(t)}(this),this._watchPaths=ea(this,e),this._initialized&&null!==this._rootNode&&!t()&&(ra(this),Gi(this),this._streamsStartedGeneration=this._connectGeneration),this._resolveLoading?.()}get name(){return this._name}_loadFromSsrElement(){if(!this.hasAttribute("enable-ssr"))return null;const t=this.getAttribute("name")||"default",e=this.parentNode;if(!e)return null;const n=Hr.findByName(e,t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null}async _initialize(){const n=t()?null:this._loadFromSsrElement();try{if(this.hasAttribute("state")){const t=this.getAttribute("state");this._state=function(t){const e=document.getElementById(t);if(e&&"application/json"===e.type)try{return JSON.parse(e.textContent||"{}")}catch(t){nt("Failed to parse JSON from script element:"+t)}return{}}(t)}else if(this.hasAttribute("src")){const t=this.getAttribute("src");t&&t.endsWith(".json")?this._state=await async function(t){try{const e=await fetch(t);return e.ok||nt(`Failed to fetch JSON file: ${e.statusText}`),await e.json()}catch(t){return console.error("Failed to load JSON file:",t),{}}}(t):t&&t.endsWith(".js")?this._state=await Ni(t):nt(`Unsupported src file type: ${t}`)}else if(this.hasAttribute("json")){const t=this.getAttribute("json");this._state=JSON.parse(t)}else{const t=this.querySelector('script[type="module"]');if(t)this._state=await vi(t,`${this._name}`);else{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${e.tagNames.state}> element with name="${this._name}".`)},6e4);this._state=await this._setStatePromise,clearTimeout(t)}}}catch(t){nt(`Failed to initialize state: ${t}`)}if(null!==n&&this.__state)for(const[t,e]of Object.entries(n)){if(t in this.__state){const e=Object.getOwnPropertyDescriptor(this.__state,t);if(e&&(e.get||e.set))continue;if("function"==typeof this.__state[t])continue}this.__state[t]=e}await this._loadingPromise,this._name=this.getAttribute("name")||"default",ni(this.rootNode,this._name,this)}async _initializeBindWebComponent(){if(this.hasAttribute("bind-component")){const t=this.parentNode,n=t instanceof ShadowRoot?t.host:t instanceof Element?t:null,o=n?G(n):null;null!==n&&null!==o||nt(`"bind-component" requires <${e.tagNames.state}> to be a direct child of a custom element.`),t instanceof ShadowRoot||this.hasAttribute("name")||nt('"bind-component" in Light DOM requires a "name" attribute to avoid namespace conflicts with the parent scope.');const s=["state","src","json"].filter(t=>this.hasAttribute(t));null!==this.querySelector('script[type="module"]')&&s.push('<script type="module">'),s.length>0&&nt(`"bind-component" cannot be combined with ${s.join(", ")}. The component's "${this.getAttribute("bind-component")}" property is the only state source.`);const r=this.getAttribute("bind-component"),i=J(n);null===i&&nt(`CustomElementRegistry is unavailable for <${o}>.`),await i.whenDefined(o.toLowerCase()),n.hasAttribute(e.bindAttributeName)&&await B(n),r in n||nt(`Component does not have property "${r}" for state binding.`);const a=n[r];"object"==typeof a&&null!==a||nt(`Component property "${r}" is not an object for state binding.`),this._boundComponent=n,this._boundComponentStateProp=r,gl(this,this._boundComponent,this._boundComponentStateProp,a)}}_initializeLightDomComponentScope(){const t=this._boundComponent;null!==t&&this.parentNode===t&&t.hasAttribute(e.bindAttributeName)&&(Rr(this._rootNode,t),mr(t,null))}_reloadMappedPathsAfterReconnect(){if(!this._hasMappedComponentState||null===this._boundComponent)return;const t=function(t){const e=Qn.get(t);if(void 0===e)return[];const n=[];for(const t of e)n.push(t.innerAbsPathInfo.pathInfo.path);return n}(this._boundComponent);!function(t){const e=Qn.get(t);if(void 0===e)return;const n=new Map,o=new Map;for(const t of e)n.set(t.innerAbsPathInfo,t.outerAbsPathInfo),o.set(t.outerAbsPathInfo,t.innerAbsPathInfo);Xn.set(t,n),Yn.set(t,o)}(this._boundComponent),this.createState("readonly",e=>{for(const n of t)e.$postUpdate(n)})}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{N in t&&await t[se]()})}async _initializeDCC(t,n){let o;try{if(this.hasAttribute("src")){const t=this.getAttribute("src");t.endsWith(".js")?o=await Ni(t):nt(`DCC: Unsupported src type: ${t}`)}else{const e=this.querySelector('script[type="module"]');e?o=await vi(e,t.tagName.toLowerCase()):nt(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}}catch(t){nt(`DCC: Failed to load state: ${t}`)}!function(t,n,o){const s=t.tagName.toLowerCase();s.includes("-")||nt(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=J(t);null!==r&&"function"==typeof r.define||nt(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&nt(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template");i.innerHTML=n.innerHTML;const a=n.mode,{bindables:l,commands:c,streamBackedBindables:d}=wa(o),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=`${e.tagNames.state}:not([name])`,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(D))return null;this._shadow=this.attachShadow({mode:p.shadowRootMode}),this._shadow.appendChild(p.template.content.cloneNode(!0));const t=J(this._shadow);return null!==t&&X(t,this._shadow),this._shadow}connectedCallback(){const t=this._ensureShadow();if(null!==t&&Object.keys(p.bindableEventMap).length>0){const n=t.querySelector(h);n?n.setBindableEventMap(p.bindableEventMap):console.warn(`[@wcstack/state] DCC: "${s}" declares ${$} but its template has no <${e.tagNames.state}> without a "name" attribute. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(h)??null}},m=ga(o);for(const[t,e]of Object.entries(m)){if(ma(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=pa(t,o)}else n.get=fa(t),n.set=ha(t);Object.defineProperty(p.prototype,t,n)}for(const t of d)Object.defineProperty(p.prototype,t,{configurable:!0,enumerable:!0,get:fa(t),set:ha(t)});r.define(s,p)}(t,n,o),this._dcc=!0,this._initialized=!0,this._rootNode=null,this._resolveInitialize?.(),this._resolveConnectedCallback?.()}_callStateDisconnectedCallback(){this.createState("writable",t=>{S in t&&t[re]()})}async connectedCallback(){this._rootNode=this.getRootNode();const n=++this._connectGeneration;if(this._initialized)this._dcc||ti(this._rootNode,this._name)===this||(ni(this._rootNode,this._name,this),this._reloadMappedPathsAfterReconnect());else{const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(D))return this.hasAttribute("bind-component")&&nt(`"bind-component" cannot be used inside a [${D}] host. DCC state comes from the template, not from a component property.`),void await this._initializeDCC(t.host,t);await this._initializeBindWebComponent(),await this._initialize(),this._initialized=!0,this._initializeLightDomComponentScope(),this._resolveInitialize?.()}if(this.hasAttribute("enable-ssr")&&!t()||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr"))try{await ei(this.rootNode);const t=this.getAttribute("name")||"default",n=Hr.extractStateData(this),o=document.createElement(e.tagNames.ssr);o.setAttribute("name",t),o.setAttribute("version",jr),Hr.buildContent(o,n),this.parentNode?.insertBefore(o,this)}catch(t){throw this._rejectConnectedCallback?.(t),t}t()||null===this._rootNode||n!==this._connectGeneration||ra(this),t()||null===this._rootNode||n!==this._connectGeneration||this._streamsStartedGeneration===n||Gi(this),this._resolveConnectedCallback?.()}disconnectedCallback(){if(null!==this._rootNode)try{this._callStateDisconnectedCallback()}finally{ni(this.rootNode,this._name,null),t=this,Ii.delete(t),function(t){$i.delete(t)}(this),Ze(this),Ri(this),Ui(this),function(t){Yi.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}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&&nt("State rootNode is not available."),this._rootNode}get hasRootNode(){return null!==this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get boundComponent(){return this._boundComponent}get hasMappedComponentState(){return this._hasMappedComponentState}markComponentStateMapped(){this._hasMappedComponentState=!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){const e=!this._listPaths.has(t);this._listPaths.add(t),this._elementPaths.add(t+"."+o),e&&this._hasMappedComponentState&&function(t,e){const n=oo(t,U(e));null!==n&&n.stateElement!==t&&n.stateElement.setPathInfo(n.pathInfo.path,"for","internal")}(this,t)}if(!this._pathSet.has(t)){const e=U(t);if(this._pathSet.add(t),er(this,this.__state,t,n),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=U(t.parentPath)}}}_createState(t,e,n){try{const o=function(t,e,n,o){const s=new ul(t,n,o);return new Proxy(e,s)}(t,this._state,this._name,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)}bindProperty(t,e){Object.defineProperty(this._state,t,e),t===I&&(this._hasUpdatedCallback=!0)}setInitialState(t){this._initialized?this._state=t:this._resolveSetState?.(t)}}function bl(t=customElements){t.get(e.tagNames.ssr)||t.define(e.tagNames.ssr,Hr),t.get(e.tagNames.state)||t.define(e.tagNames.state,yl)}var wl;await(bl(wl),void bi());
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="|",c="prevent",d="stop",u="ro",f="init",h="sync",p="else",m="...",g="on",b="eventToken",y="command",w="class",v="attr",N="style",S={};for(let t=0;t<128;t++)S[`$${t+1}`]=t;const $=Object.freeze(S),I="$connectedCallback",x="$disconnectedCallback",P="$updatedCallback",_="$stateReadyCallback",A="$bindables",k="$commands",C="$commandTokens",E="$command",M="$eventTokens",T="$on",O="$streams",R="$watch",D="$listKeys",L="$streamStatus",j="$streamError",W="data-wc-definition",B=new WeakMap,F=new WeakSet;let z=0;async function q(t){const e=function(t){let e,n=B.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++z,promise:o,resolve:e},B.set(t,n),F.has(t)&&n.resolve(),n}(t);await e.promise}function U(t){const e=B.get(t);void 0===e?F.add(t):e.resolve()}const V=new Map;let H=0;function G(t){let e=V.get(t);return void 0!==e||(e=Object.freeze(new K(t)),V.set(t,e)),e}class K{id=++H;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:G(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 J=new WeakMap;function X(t){const e=J.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{J.set(t,n)}}function Y(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function Q(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return Y(e);if(void 0!==n)return Y(n)}return Y(globalThis.customElements)}function Z(t,e){t.upgrade?.(e)}function tt(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=st(s.properties,et);if(null===r)return null;const i=void 0===s.inputs?new Map:st(s.inputs,nt);if(null===i)return null;const a=void 0===s.commands?new Map:st(s.commands,ot);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function et(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 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.attribute||"string"==typeof e.attribute)}function ot(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 st(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 rt(t){throw new Error(`[@wcstack/state] ${t}`)}function it(t,e,n){const o="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:o,statePathInfo:G(o),stateName:n,inFilters:[],outFilters:[],bindingType:"prop"}}function at(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function lt(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&&rt("Spread binding requires an element node.");const e=t,o=X(e);null===o&&rt(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=Q(e);null===a&&rt(`CustomElementRegistry is unavailable for <${o}>.`);if(void 0===a.get(o)){s||rt(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Z(a,e);const l=tt(e);null===l&&rt(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=n.stateName,u=new Set;for(const t of l.knownProperties.keys()){if(u.has(t))continue;u.add(t);const e=it(t,c,d);i.add(e),r.push(e)}for(const t of l.declaredInputs.keys()){if(u.has(t))continue;u.add(t);const e=it(t,c,d);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=at(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=at(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 ct(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 dt=new WeakMap;function ut(t){return dt.get(t)||null}function ft(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 ht(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=ft(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const pt=" Validate statically: npx @wcstack/lint <file>.",mt=new Set(["if","elseif","else","for"]);function gt(t){rt(`filter ${t} requires at least one option`)}function bt(t){rt(`filter ${t} requires a number as option`)}function yt(t){rt(`filter ${t} requires a number value`)}function wt(t){rt(`filter ${t} requires a date value`)}function vt(t){return!(!t||isNaN(Number(t)))}const Nt={eq:t=>{const e=t?.[0]??gt("eq");return t=>"number"==typeof t?(vt(e)||bt("eq"),t===Number(e)):t===e},ne:t=>{const e=t?.[0]??gt("ne");return t=>"number"==typeof t?(vt(e)||bt("ne"),t!==Number(e)):t!==e},not:t=>t=>("boolean"!=typeof t&&rt(`filter ${"not"} requires a boolean value`),!t),lt:t=>{const e=t?.[0]??gt("lt");return vt(e)||bt("lt"),t=>("number"!=typeof t&&yt("lt"),t<Number(e))},le:t=>{const e=t?.[0]??gt("le");return vt(e)||bt("le"),t=>("number"!=typeof t&&yt("le"),t<=Number(e))},gt:t=>{const e=t?.[0]??gt("gt");return vt(e)||bt("gt"),t=>("number"!=typeof t&&yt("gt"),t>Number(e))},ge:t=>{const e=t?.[0]??gt("ge");return vt(e)||bt("ge"),t=>("number"!=typeof t&&yt("ge"),t>=Number(e))},inc:t=>{const e=t?.[0]??gt("inc");return vt(e)||bt("inc"),t=>("number"!=typeof t&&yt("inc"),t+Number(e))},dec:t=>{const e=t?.[0]??gt("dec");return vt(e)||bt("dec"),t=>("number"!=typeof t&&yt("dec"),t-Number(e))},mul:t=>{const e=t?.[0]??gt("mul");return vt(e)||bt("mul"),t=>("number"!=typeof t&&yt("mul"),t*Number(e))},div:t=>{const e=t?.[0]??gt("div");return vt(e)||bt("div"),t=>("number"!=typeof t&&yt("div"),t/Number(e))},mod:t=>{const e=t?.[0]??gt("mod");return vt(e)||bt("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]??gt("clamp");vt(e)||bt("clamp");const n=t?.[1]??gt("clamp");vt(n)||bt("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 vt(e)||bt("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]??gt("slice");vt(n)||bt("slice"),e.push(Number(n));const o=t?.[1];return void 0!==o&&(vt(o)||bt("slice"),e.push(Number(o))),t=>String(t).slice(...e)},substr:t=>{const e=t?.[0]??gt("substr");vt(e)||bt("substr");const n=t?.[1]??gt("substr");return vt(n)||bt("substr"),t=>String(t).substr(Number(e),Number(n))},pad:t=>{const e=t?.[0]??gt("pad");vt(e)||bt("pad");const n=t?.[1]??"0";return t=>String(t).padStart(Number(e),n)},rep:t=>{const e=t?.[0]??gt("rep");return vt(e)||bt("rep"),t=>String(t).repeat(Number(e))},rev:t=>t=>String(t).split("").reverse().join(""),truncate:t=>{const e=t?.[0]??gt("truncate");vt(e)||bt("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)||rt(`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 vt(e)||bt("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 vt(e)||bt("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 vt(e)||bt("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 vt(e)||bt("percent"),t=>("number"!=typeof t&&yt("percent"),`${(100*t).toFixed(Number(e))}%`)},unit:t=>{const e=t?.[0]??gt("unit");return t=>null==t?t:String(t)+e},date:t=>{const e=t?.[0];return t=>(t instanceof Date||wt("date"),t.toLocaleDateString(e??o.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||wt("time"),t.toLocaleTimeString(e??o.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||wt("datetime"),t.toLocaleString(e??o.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||wt("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||wt("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]??gt("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},St=Nt,$t={input:Nt,output:St},It=(t,e)=>n=>{const o=n[t];return o||rt(`[wcs/filter-unknown] filter not found: ${t}.${ht(t,Object.keys(n))}${pt}`),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 Pt=new Map;function _t(t,e){const n=$t[e];return t.map(t=>{const o=t.indexOf("("),s=t.lastIndexOf(")");if(-1!==o&&-1===s&&rt(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==s&&-1===o&&rt(`Invalid filter format: missing opening parenthesis in "${t}"`),-1===o){const o=t.trim(),s=`${o}():${e}`;let r=Pt.get(s);return void 0===r&&(r=It(o,[])(n),Pt.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=Pt.get(l);return void 0===c&&(c=It(i,a)(n),Pt.set(l,c)),{filterName:i,args:a,filterFn:c}}})}const At=t=>t.trim(),kt=new Map;const Ct=new Set;function Et(t,e){if(!o.debug)return;const n=`${t}:${e}`;if(Ct.has(n))return;Ct.add(n);const s="attribute"===t?`<wcs-state name="${e}"> will be removed in v2. Mount the state onto the root tree with <wcs-state mount="${e}"> and read it as "${e}.<path>".`:`"${e}" uses the "@name" state selector, which will be removed in v2. Read the mounted tree as "<name>.<path>" instead.`;console.warn(`[@wcstack/state] [wcs/named-state-deprecated] ${s} See docs/state-mount-design.md §9.`)}const Mt=new Map;function Tt(t){const e=t.indexOf(l);let n="",o=[],s="",r=[];-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),Mt.has(s)?r=Mt.get(s):(o=s.split(l).map(At),r=_t(o,"output"),Mt.set(s,r))):n=t.trim(),-1!==n.indexOf(a)&&Et("path",n);const[i,c="default"]=n.split(a).map(At);return{stateName:c,statePathName:i,statePathInfo:G(i),outFilters:r}}function Ot(t){const[...e]=t.split(";").map(At).filter(t=>t.length>0),n=e.map(t=>{const e=t.indexOf(":");-1===e&&rt(`Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim();if(n===p){const t=G("#else");return{propName:p,propSegments:[p],propModifiers:[],statePathName:"#else",statePathInfo:t,stateName:"",inFilters:[],outFilters:[],bindingType:"else"}}if(n===m){const e=Tt(o);return e.outFilters.length>0&&rt(`Invalid spread binding "${t}": filters are not allowed on spread targets.`),0===e.statePathName.length&&rt(`Invalid spread binding "${t}": spread target path is required.`),{propName:m,propSegments:[m],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n||"radio"===n||"checkbox"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Tt(o),bindingType:n}}{const t=Tt(o),e=function(t){const e=t.indexOf(l);let n="",o=[],r="",i=[];-1!==e?(n=t.slice(0,e).trim(),r=t.slice(e+1).trim(),kt.has(r)?i=kt.get(r):(o=r.split(l).map(At),i=_t(o,"input"),kt.set(r,i))):n=t.trim();const[a,c]=n.split("#").map(At),d=a.split(s).map(At);return{propName:a,propSegments:d,propModifiers:c?c.split(",").map(At):[],inFilters:i}}(n);return e.propSegments[0]===b||e.propSegments[0].startsWith(g)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});if(n.length>1){n.some(t=>mt.has(t.bindingType))&&rt(`[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">).${pt}`)}return n}const Rt=new WeakMap,Dt=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Lt=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function jt(t){const e=Rt.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),s=Lt.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Dt.has(r)?(Rt.set(t,s[2]),s[2]):null}function Wt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Tt(t),bindingType:"text"}}const Bt=new Map;function Ft(t,e,n){if(null===n)Bt.delete(t);else{Bt.set(t,n);const o=n.parseBindTextResult,s=Ti(e,o.stateName);null===s&&rt(`State element with name "${o.stateName}" not found for fragment info.`),s.setPathInfo(o.statePathName,o.bindingType);for(const t of n.nodeInfos)for(const n of t.parseBindTextResults){const t=Ti(e,n.stateName);null===t&&rt(`State element with name "${n.stateName}" not found for fragment info node.`),t.setPathInfo(n.statePathName,n.bindingType)}}}function zt(t){return Bt.get(t)||null}function qt(t){if(t.nodeType===Node.ELEMENT_NODE){return Ot(t.getAttribute(o.bindAttributeName)||"")}if(t.nodeType===Node.COMMENT_NODE){const e=jt(t);null===e&&rt("Comment node binding text not found.");const n=zt(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Wt(e),s=null):s=e,[{...o,uuid:s}]}return[]}function Ut(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(o.bindAttributeName)}function Vt(t){const e=[],n=t.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!Ut(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function Ht(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 Gt(t){const e=[],n=Vt(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!==jt(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const t=s.currentNode;n.length>0&&Ht(t,n)||e.push(t)}return e}const Kt=new WeakSet;function Jt(t,e,n){const o=lt(t,e,{allowDeferred:n.allowDeferred});if(o.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?X(t):null;return null===n&&rt("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e}}}Kt.add(t);const s=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,o);return function(t,e){dt.set(t,e)}(t,s),U(t),{bindings:s,deferred:null}}function Xt(t){const e=Gt(t),n=[],o=[];for(const t of e){if(Kt.has(t))continue;const e=Jt(t,qt(t),{allowDeferred:!0});null===e.deferred?n.push(...e.bindings):o.push(e.deferred)}return[e,n,o]}function Yt(t){Kt.add(t)}function Qt(t){const{node:e,parseResults:n}=t;!function(t){Kt.delete(t)}(e);return Jt(e,n,{allowDeferred:!1}).bindings}const Zt=new WeakMap;function te(t){let e=t;for(;e;){const t=Zt.get(e);if(t)return t;e=e.parentNode}return null}function ee(t,e){null!==e?Zt.set(t,e):Zt.delete(t)}let ne=null;const oe=new WeakMap;function se(t){return oe.get(t)??[]}function re(t,e){oe.set(t,e)}const ie=Symbol("$$setLoopContext"),ae=Symbol("$$getByAddress"),le=Symbol("$$hasByAddress"),ce=Symbol("$$setByAddress"),de=Symbol("$$connectedCallback"),ue=Symbol("$$disconnectedCallback"),fe=Symbol("$$updatedCallback"),he=new WeakMap;function pe(t,e){if(he.has(t)){const n=he.get(t);if(n.has(e))return n.get(e)}else he.set(t,new WeakMap);const n=Object.freeze(new me(t,e));return he.get(t).set(e,n),n}class me{pathInfo;stateName;stateElement;parentAbsolutePathInfo;constructor(t,e){this.pathInfo=e,this.stateName=t.name,this.stateElement=t,null===e.parentPathInfo?this.parentAbsolutePathInfo=null:this.parentAbsolutePathInfo=pe(t,e.parentPathInfo)}}const ge=new WeakMap,be=new WeakMap;class ye{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=be.get(t);return void 0!==e||(e=new ye(t,null),be.set(t,e)),e}{let n=ge.get(e);void 0===n&&(n=new WeakMap,ge.set(e,n));let o=n.get(t);return void 0!==o||(o=new ye(t,e),n.set(t,o)),o}}const ve=new WeakMap;function Ne(t,e){null===e?ve.delete(t):ve.set(t,e)}function Se(t){return ve.get(t)||null}const $e=new Map;function Ie(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=$e.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,$e.set(s,r),r}function xe(t,e,n){return e<0||e>=n?null:t.at(e-n)}function Pe(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const _e=new WeakMap;function Ae(t){const e=te(t.node);if(null===e)return null;let n=_e.get(e);if(void 0===n)n=new WeakMap,_e.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=Ie(e.pathInfo,t.statePathInfo);return n>0&&(o=xe(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const ke=new WeakMap;function Ce(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=Se(n);null===e?rt(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function Ee(t,e){let n=null;if(n=ke.get(t)||null,null!==n)return n;const o=Ce(t,e),s=Ae(t),r=Ti(o,t.stateName);null===r&&rt(`State element with name "${t.stateName}" not found for binding.`);return n=we(pe(r,t.statePathInfo),s),ke.set(t,n),n}function Me(t){ke.delete(t)}const Te=new WeakMap;function Oe(t,e){const n=Te.get(t);void 0===n?Te.set(t,e):n instanceof Set?n.add(e):n!==e&&Te.set(t,new Set([n,e])),null!==ne&&ne({type:"state:binding-added",absoluteAddress:t,binding:e})}function Re(t,e){const n=Te.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&Te.delete(t),null!==ne&&ne({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const De=new WeakMap;function Le(t,e,n){let o=De.get(t);void 0===o&&(o=new WeakMap,De.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!==ne&&ne({type:"state:binding-added",absoluteAddress:we(t,e),binding:n})}function je(t,e,n){const o=De.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!==ne&&ne({type:"state:binding-removed",absoluteAddress:we(t,e),binding:n}))}function We(t){const e=Te.get(t);return void 0!==e?e:null!==t.listIndex?De.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const Be=new WeakMap,Fe=new WeakMap;class ze{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=qe(t,e)}}function qe(t,e){if(null===e){let e=Fe.get(t);return void 0!==e||(e=new ze(t,null),Fe.set(t,e)),e}{let n=Be.get(e);void 0===n&&(n=new WeakMap,Be.set(e,n));let o=n.get(t);return void 0!==o||(o=new ze(t,e),n.set(t,o)),o}}const Ue=new WeakMap;function Ve(t){let e=null;if(e=Ue.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=Ae(t);null===n&&rt(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=qe(t.statePathInfo,n)}else e=qe(t.statePathInfo,null);return Ue.set(t,e),e}function He(t){Ue.delete(t)}function Ge(){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 Ke=new Map,Je=Ge();function Xe(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.stateName}::${t.statePathName}::${e}::${n}`}function Ye(t){let e="input";for(const n of t.propModifiers)n.startsWith(g)&&(e=n.slice(2));return e}function Qe(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(u)){const s=Ye(t),r=Xe(t,s);let i=Ke.get(r);return void 0===i&&(e=t.stateName,n=t.statePathName,o=t.inFilters,i=t=>{const s=t.target;if(null===s)return void console.warn("[@wcstack/state] event.target is null.");if("checkbox"!==s.type)return void console.warn("[@wcstack/state] event.target is not a checkbox input element.");const r=s.checked;let i=s.value;for(const t of o)i=t.filterFn(i);const a=Ti(s.getRootNode(),e);null===a&&rt(`State element with name "${e}" not found for two-way binding.`);const l=te(s);a.createState("writable",t=>{t[ie](l,()=>{let e=t[n];if(Array.isArray(e))if(r)-1===e.indexOf(i)&&(t[n]=e.concat(i));else{const o=e.indexOf(i);-1!==o&&(t[n]=e.toSpliced(o,1))}else t[n]=r?[i]:[]})})},Ke.set(r,i)),t.node.addEventListener(s,i),Je.add(r,t),!0}var e,n,o;return!1}function Ze(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function tn(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)Ze(t)&&Promise.resolve(t).catch(t=>{console.error(`[wcstack/state] ${e} rejected.`,t)})}class en{_name;_subscribers=new Set;constructor(t){this._name=t}get name(){return this._name}get size(){return this._subscribers.size}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}unsubscribe(t){return this._subscribers.delete(t)}emit(...t){const e=[];for(const n of this._subscribers)e.push(n(...t));return e}}class nn extends en{_ownerStateName;constructor(t,e){super(t),this._ownerStateName=e??null}emit(...t){return null!==ne&&ne({type:"state:token-emit",kind:"event",stateName:this._ownerStateName,tokenName:this.name,args:t,subscriberCount:this.size}),super.emit(...t)}}const on=new WeakMap;function sn(t,e){let n=on.get(t);void 0===n&&(n=new Map,on.set(t,n));let o=n.get(e);return void 0===o&&(o=new nn(e,t.name),n.set(e,o)),o}function rn(t){on.delete(t)}const an=new WeakMap;function ln(t){if(t.propSegments[0]!==b)return!1;const e=t.node,n=X(e),o=Q(e);if(null!==n&&void 0===o?.get(n))return null===o&&rt(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(an.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||rt('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===X(t)?null:tt(t)}(e);null===r&&rt(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&rt(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${ht(s,r.knownProperties.keys())}`);const a=i.event,l=t.statePathName,u=t.stateName,f=t.propModifiers,h=t=>{f.includes(c)&&t.preventDefault(),f.includes(d)&&t.stopPropagation();const n=Ti(e.getRootNode(),u);null===n&&rt(`State element with name "${u}" not found for eventToken handler.`),n.eventTokenNames.has(l)||rt(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens of state "${u}".${ht(l,n.eventTokenNames)}${pt}`);const o=te(e);n.createStateAsync("writable",async e=>{tn(e[ie](o,()=>{const s=null!==o?Pe(o.listIndex,o.pathInfo.wildcardCount):[];return sn(n,l).emit(e,t,...s)}),`$on."${l}" of state "${u}"`)})};return e.addEventListener(a,h),an.set(t,{eventName:a,handler:h}),!0}class cn extends en{_ownerStateName;constructor(t,e){super(t),this._ownerStateName=e??null}emit(...t){return null!==ne&&ne({type:"state:token-emit",kind:"command",stateName:this._ownerStateName,tokenName:this.name,args:t,subscriberCount:this.size}),super.emit(...t)}}function dn(t){return t instanceof cn}const un=new Map,fn=Ge();function hn(t){const e=t.propModifiers.filter(t=>t===c||t===d).sort().join(",");return`${t.stateName}::${t.statePathName}::${e}`}const pn=(t,e,n,o)=>s=>{n.includes(c)&&s.preventDefault(),n.includes(d)&&s.stopPropagation();const r=s.target,i=Ti(r.getRootNode(),t);null===i&&rt(`State element with name "${t}" not found for event handler.`);const a=te(r),l=e.startsWith(E+".");i.createStateAsync("writable",async n=>{tn(n[ie](a,()=>{const r=null!==a?Pe(a.listIndex,a.pathInfo.wildcardCount):[];if(l){const t=n[ae](qe(o,null));return dn(t)||rt(`Event binding "${e}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),t.emit(s,...r)}const i=n[e];return"function"!=typeof i&&rt(`Handler "${e}" is not a function on state "${t}".`),Reflect.apply(i,n,[s,...r])}),`"${e}" of state "${t}"`)})};function mn(t){if(!t.propName.startsWith(g))return!1;const e=hn(t);let n=un.get(e);void 0===n&&(n=pn(t.stateName,t.statePathName,t.propModifiers,t.statePathInfo),un.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),fn.add(e,t),!0}const gn=new Map,bn=Ge();function yn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.stateName}::${t.statePathName}::${e}::${n}`}function wn(t){let e="input";for(const n of t.propModifiers)n.startsWith(g)&&(e=n.slice(2));return e}function vn(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(u)){const s=wn(t),r=yn(t,s);let i=gn.get(r);return void 0===i&&(e=t.stateName,n=t.statePathName,o=t.inFilters,i=t=>{const s=t.target;if(null===s)return void console.warn("[@wcstack/state] event.target is null.");if("radio"!==s.type)return void console.warn("[@wcstack/state] event.target is not a radio input element.");if(!1===s.checked)return;let r=s.value;for(const t of o)r=t.filterFn(r);const i=Ti(s.getRootNode(),e);null===i&&rt(`State element with name "${e}" not found for two-way binding.`);const a=te(s);i.createState("writable",t=>{t[ie](a,()=>{t[n]=r})})},gn.set(r,i)),t.node.addEventListener(s,i),bn.add(r,t),!0}var e,n,o;return!1}const Nn=new Set(["radio","checkbox"]),Sn=new Set(["value","valueAsNumber","valueAsDate"]);function $n(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(Nn.has(t)&&"checked"===e)return!0;if(Sn.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=X(n);if(null!==s){const t=Q(n)?.get(s);void 0===t&&rt(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=tt(n);if(o?.knownProperties.has(e))return!0}return!1}let In=1,xn=1,Pn=1;const _n=new WeakMap;function An(t,e,n,o){let s=_n.get(t);void 0===s&&(s=new Map,_n.set(t,s));const r=function(t,e,n){return`${e}::${n}::${t}`}(e,n,o);let i=s.get(r);return void 0===i&&(i=In++,s.set(r,i)),i}function kn(t,e){return"to-element"===e?2*t:2*t+1}const Cn=new Set;function En(t){return{transactionId:xn++,originBindingId:t,visitedEdges:Cn,hop:0}}function Mn(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 Tn=null;function On(){return Tn}function Rn(t,e){const n=Tn;Tn=t;try{return e()}finally{Tn=n}}const Dn=[];let Ln=!1;const jn=new Map,Wn=Ge(),Bn=new WeakMap,Fn=t=>t.detail;function zn(t,e,n,o){const s=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.stateName}::${t.propName}::${t.statePathName}::${e}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function qn(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=X(t.node);if(null!==n){const o=Q(t.node)?.get(n);void 0===o&&rt(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=tt(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(g)&&(e=n.slice(2));return e}function Un(t){if(null!==X(t.node)){const e=tt(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??Fn}return null}function Vn(t){if(null===X(t.node))return!1;const e=tt(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}const Hn=(t,e,n,s,r,i)=>a=>{const l=a.target;if(null===l)return void console.warn("[@wcstack/state] event.target is null.");let c;if(null!==r)c=r(a);else{if(!(e in l))return void console.warn(`[@wcstack/state] Property "${e}" does not exist on target element.`);c=l[e]}let d=c;for(const t of s)d=t.filterFn(d);const u=Bn.get(l)?.get(e);if(void 0!==u)for(const t of u)t(d);let f=null;if(o.enablePropagationContext){const s=An(l,e,t,n),r=function(t,e){for(let n=Dn.length-1;n>=0;n--){const o=Dn[n];if(o.node===t&&o.receipt.member===e)return o.receipt}return null}(l,e);if(null!==r&&Object.is(r.writtenValue,c))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:l,propName:e,statePathName:n,transactionId:r.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===d||"object"!=typeof d)}),void(null!==ne&&ne({type:"propagation:suppressed",reason:"confirmation",transactionId:r.transactionId,edgeId:kn(s,"to-state"),node:l,member:e}));const i=kn(s,"to-state"),a=On();if(null!==a&&a.visitedEdges.has(i))return void(null!==ne&&ne({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:i,node:l,member:e}));f=Mn(a??En(s),i)}const h=Ti(l.getRootNode(),t);null===h&&rt(`State element with name "${t}" not found for two-way binding.`);const p=te(l),m=()=>{i&&(Ln=!0);try{h.createState("writable",t=>{t[ie](p,()=>{t[n]=d})})}finally{i&&(Ln=!1)}};null!==f?Rn(f,m):m()};const Gn=new WeakMap;function Kn(t,e){const n=Gn.get(t);return n?n.get(e)??null:null}const Jn=new WeakMap;function Xn(t,e){Jn.set(t,e)}function Yn(t){return Jn.get(t)??null}function Qn(t){let e=t;for(;;){if(null==e||!0!==e.hasMappedComponentState)return null;const t=e.boundComponent;if(null==t)return null;const n=te(t)?.listIndex;if(null!=n)return n;e=Yn(t)}}function Zn(t){return Qn(t)?.length??0}function to(t,e){return e.wildcardCount+Zn(t)}function eo(t,e){return e??Qn(t)}const no=new WeakMap,oo=new WeakMap,so=new WeakMap,ro=new WeakMap;function io(t,e){const n=e.propSegments.slice(1).join(s);return{innerAbsPathInfo:pe(t,G(n)),outerAbsPathInfo:Ee(e).absolutePathInfo,isRoot:0===n.length}}function ao(t){return so.get(t)??null}function lo(t){const e=so.get(t);if(void 0===e)return!1;for(const t of e)if(t.isRoot)return!0;return!1}function co(t,e,n=!0){let r=no.get(t);if(void 0===r&&(r=new Map,no.set(t,r)),r.has(e))return r.get(e);let i=oo.get(t);void 0===i&&(i=new Map,oo.set(t,i));const a=so.get(t);if(void 0===a)return null;let l=null,c=-1;for(const t of a){if(t.isRoot){c<0&&(l=t,c=0);continue}if(!e.pathInfo.cumulativePathInfoSet.has(t.innerAbsPathInfo.pathInfo))continue;const n=t.innerAbsPathInfo.pathInfo.segments.length;n===e.pathInfo.segments.length&&rt("Duplicate mapping rule for web component."),n>c&&(l=t,c=n)}if(null===l)return null;const d=ro.get(l);void 0===d&&rt("Binding not found for primary mapping rule on web component.");const u=e.pathInfo.segments.slice(c),f=G(l.outerAbsPathInfo.pathInfo.segments.concat(u).join(s)),h=Ti(t.getRootNode(),d.stateName);null===h&&rt(`State element with name "${d.stateName}" not found for web component.`);const p=pe(h,f);if(!n)return p;r.set(e,p),i.set(p,e);const m=[d.propSegments[0],...e.pathInfo.segments],g={...d,propName:m.join(s),propSegments:m,statePathName:p.pathInfo.path,statePathInfo:p.pathInfo},b=e=>{o.debug&&console.warn(`parent→child notification for "${p.pathInfo.path}" is not registered: ${e}.`,{webComponent:t,primaryBinding:d})},y=Xo(d);return null===y?(b("no binding session for the primary mapping rule"),p):p.pathInfo.wildcardCount>0&&null===Ae(g)?(b("the derived outer path is a wildcard path but no list index resolves from the component"),p):(y.initialize([g],{registerAddress:!0}),p)}function uo(t,e){const n=fo(t,e);if(null===n||n.stateElement===t)return null;return to(t,e)!==to(n.stateElement,n.pathInfo)?null:n}function fo(t,e){if(!0!==t.hasMappedComponentState)return null;const n=t.boundComponent;if(null==n)return null;return co(n,pe(t,e),!1)}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 bo(t){go.add(t)}function yo(t){return!!go.has(t)&&(go.delete(t),!0)}let wo=0;function vo(){wo--}function No(){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 $o=new WeakMap;function Io(t){let e=$o.get(t);return void 0===e&&(e=new So(t),$o.set(t,e)),e}function xo(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!==f&&s!==h&&rt(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&rt(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function Po(t){return t.propModifiers.some(t=>t.includes("="))}const _o=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Ao=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function ko(t,e){return"state"===t&&"call"===e?_o:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function Co(t){if(!o.enableDirectionalInitialSync)return Po(t)&&rt("init=/sync= modifiers require enableDirectionalInitialSync."),_o;const e=null===(n=xo(t,f))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:rt(`Invalid init modifier value "${n}".`);var n;const s=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":rt(`Invalid sync modifier value "${t}".`)}(xo(t,h));if("event"===t.bindingType)return null!==e&&"none"!==e&&rt("Event bindings only allow init=none."),"call"===s?Ao:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(t.propSegments[0]===y)return ko("state",s);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&rt(`Binding type "${t.bindingType}" does not support init=${e}.`),ko(e??"state",s);const r=tt(t.node);if(null===r)return ko(e??"state",s);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||rt(`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)||rt(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==s||i||rt(`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=Ti(t.replaceNode.getRootNode(),t.stateName);null===e&&rt(`State element with name "${t.stateName}" not found for binding.`);const n=Ve(t);let o=!1;return e.createState("readonly",t=>{o=t[le](n)}),o}(t)?"state":"element"}let Mo=0,To=0;const Oo=new WeakMap,Ro=new WeakMap,Do=new WeakMap,Lo=new WeakMap;function jo(t,e){const n=Lo.get(t);void 0!==n?n!==e&&(n instanceof Set?n.add(e):Lo.set(t,new Set([n,e]))):Lo.set(t,e)}function Wo(t){return Lo.has(t)}function Bo(t,e){const n=Lo.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)yo(t)&&!No()||Fo(t,t=>{Bo(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&Lr(o)}}const Uo=new WeakMap;function Vo(t){let e=Uo.get(t);return void 0===e&&(e=new qo(t),Uo.set(t,e)),e}function Ho(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.stateName,t.statePathName,e,n,t.uuid??""].join("\0")}function Go(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class Ko{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)&&Vo(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=Q(t);null===s&&rt(`CustomElementRegistry is unavailable for <${e}>.`),this.observe(t),jo(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=Io(s).wait(e,()=>{if(a())try{Z(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&&(Re(t.address,t.info),t.address=null),t.phase="disposed",t.teardowns=null;this.records.clear()}observe(t){const e=function(t){const e=t.getRootNode();return zo(e)?e:null}(t);null!==e&&Vo(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&&Lr(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=Ho(e),Do.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;jo(n,this);const o=this.knownMapFor(n);let s=Do.get(t);void 0===s&&(s=Ho(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;jo(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,outerPatternPathInfo:null,outerPatternPathInfosRest: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{mn(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{mn(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,outerPatternPathInfo:null,outerPatternPathInfosRest: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;mn(e)?t.eventAttached=!0:e.propSegments[0]!==b?(vn(e)&&Go(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(u)){const e=wn(t),n=yn(t,e),o=gn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==bn.countOf(n)&&(bn.remove(n,t)&&gn.delete(n),!0))}return!1}(e)),Qe(e)&&Go(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(u)){const e=Ye(t),n=Xe(t,e),o=Ke.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==Je.countOf(n)&&(Je.remove(n,t)&&Ke.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(o.enableDirectionalInitialSync&&$n(e.node,e.propName)&&-1===e.propModifiers.indexOf(u)){const n=function(t,e,n){let o=Bn.get(t);void 0===o&&(o=new Map,Bn.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&&Bn.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=X(t.node);if(null!==e){const n=Q(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&rt(`CustomElementRegistry is unavailable for <${e}>.`))}if($n(t.node,t.propName)&&-1===t.propModifiers.indexOf(u)){const e=qn(t),n=Un(t),o=Vn(t),s=zn(t,e,null!==n,o);let r=jn.get(s);void 0===r&&(r=Hn(t.stateName,t.propName,t.statePathName,t.inFilters,n,o),jn.set(s,r)),t.node.addEventListener(e,r),Wn.add(s,t)}}(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{ln(e)&&Go(t,()=>function(t){if(t.propSegments[0]!==b)return!1;const e=an.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),an.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=X(t.info.node);if(null===n)return void e();const o=Q(t.info.node);if(null===o&&rt(`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=Io(o).wait(n,()=>{if(this.isAlive(t,s))try{Z(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=Ti(t.node.getRootNode(),t.stateName);null===o&&rt(`State element with name "${t.stateName}" not found for initial binding sync.`);const s=te(t.node);o.createState("writable",e=>{e[ie](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=Ae(n);if(null!==o){const i=Ti(Ce(n,e),n.stateName);null===i&&rt(`State element with name "${n.stateName}" not found for binding.`);const a=pe(i,n.statePathInfo);Le(a,o,n),t.patternPathInfo=a,t.patternListIndex=o;const l=(s=i,0===(r=n.statePathInfo).wildcardCount?null:uo(s,r));if(null!==l){Le(l,o,n),t.outerPatternPathInfo=l;const e=function(t){let e=null,n=t.stateElement,o=t.pathInfo;for(;;){const t=uo(n,o);if(null===t)return e;(e??=[]).push(t),n=t.stateElement,o=t.pathInfo}}(l);if(null!==e){for(let t=0;t<e.length;t++)Le(e[t],o,n);t.outerPatternPathInfosRest=e}}}else{const o=Ee(n,e);Oe(o,n),t.address=o}var s,r;if(!t.options.registerPathInfo)return;const i=Ti(n.replaceNode.getRootNode(),n.stateName);null===i&&rt(`State element with name "${n.stateName}" not found for binding.`),"event"!==n.bindingType&&i.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{Re(t.address,e),t.address=null,He(e),Me(e)}catch{}else if(null!==t.patternListIndex){if(null!==t.outerPatternPathInfo){try{je(t.outerPatternPathInfo,t.patternListIndex,e)}catch{}t.outerPatternPathInfo=null}if(null!==t.outerPatternPathInfosRest){const n=t.outerPatternPathInfosRest;for(let o=0;o<n.length;o++)try{je(n[o],t.patternListIndex,e)}catch{}t.outerPatternPathInfosRest=null}try{je(t.patternPathInfo,t.patternListIndex,e),t.patternPathInfo=null,t.patternListIndex=null,He(e),Me(e)}catch{}}if(t.twowayAttached){t.twowayAttached=!1;try{!function(t){const e=X(t.node);if(null!==e){const n=Q(t.node),o=n?.get(e);if(void 0===o)return}if($n(t.node,t.propName)&&-1===t.propModifiers.indexOf(u)){const e=qn(t),n=zn(t,e,null!==Un(t),Vn(t)),o=jn.get(n);if(void 0===o)return;t.node.removeEventListener(e,o),Wn.remove(n,t)&&jn.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(g))return!1;const e=hn(t),n=un.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);t.node.removeEventListener(o,n),0!==fn.countOf(e)&&(fn.remove(e,t)&&un.delete(e))}(e)}catch{}}}}function Jo(t){let e=Ro.get(t);return void 0===e&&(e=new Ko(t),Ro.set(t,e)),e}function Xo(t){return Oo.get(t)?.session??null}const Yo=new WeakMap;const Qo=new WeakMap;function Zo(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const ts=Object.freeze([]);const es=new WeakMap;const ns=new WeakMap;function os(t){return ns.get(t)??[]}function ss(t,e){ns.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 rs=0;function is(){return`u${(rs++).toString(36)}`}let as=0;class ls{uuid=is();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=as}get index(){return this._index}set index(t){this._index=t,this._version=++as,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=as),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 cs(t,e){return new ls(t,e)}const ds=new WeakMap;function us(t){return ds.get(t)||null}function fs(t,e){null!==e?ds.set(t,e):ds.delete(t)}const hs=new WeakMap,ps=Object.freeze([]),ms=new Set;function gs(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:ps,s=Array.isArray(n)&&n.length>0?n:ps,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:ps,o=Array.isArray(e)&&e.length>0?e:ps;let s=hs.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=us(o)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:ms,deleteIndexSet:new Set(i),addIndexSet:ms};let e=us(s);if(0===o.length){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=cs(t,n);e.push(o)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:ms,deleteIndexSet:ms,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:ms,deleteIndexSet:ms,addIndexSet:ms};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=cs(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=hs.get(t);o||(o=new WeakMap,hs.set(t,o)),o.set(e,n)}(o,s,a),fs(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 ys=new WeakMap;function ws(t){return ys.get(t)??[]}function vs(t,e){ys.set(t,e)}const Ns=new WeakMap;function Ss(t){return Ns.get(t)??null}function $s(t,e){Ns.set(t,e)}const Is=new WeakMap;function xs(t){return Is.get(t)??[]}function Ps(t,e){Is.set(t,e)}function _s(t,e){const n=xs(t);for(const t of n)ee(t,e)}function As(t,e,n){_s(t,e);const o=ws(t),s=Ss(t);null!==s&&s.activate(o,n.rootNode);for(const t of o){if(null===s){Oe(Ee(t),t)}(null===s||s.shouldApplyState(t))&&Rr(t,n)}}function ks(t){if(!t.mounted)return;const e=ws(t),n=Ss(t);for(const t of e)if(null!==n)n.disposeBinding(t);else{Re(Ee(t),t)}!function(t){const e=xs(t);for(const t of e)ee(t,null)}(t)}const Cs=new WeakMap,Es=Object.freeze(new Set);function Ms(t,e){const n=Cs.get(t);n?n.add(e):Cs.set(t,new Set([e]))}function Ts(t){const e=Cs.get(t);return void 0!==e?e:Es}function Os(t,e){const n=Cs.get(t);n&&(n.delete(e),0===n.size&&Cs.delete(t))}const Rs=new Set(["if","elseif","else","for"]);class Ds{_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)bo(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){bo(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=Ss(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=ws(this);for(const t of e)if(Rs.has(t.bindingType)){const e=Ts(t.node);for(const t of e)t.tryDestroy()||t.unmount()}return this._mounted=!1,!0}unmount(){Ss(this)?.dispose();for(const t of this._childNodeArray)po(t),null!==t.parentNode&&t.parentNode.removeChild(t);const t=ws(this);for(const e of t){if(Rs.has(e.bindingType)){const t=Ts(e.node);for(const e of t)e.unmount()}He(e),Me(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 js(t){const e=document.createDocumentFragment(),n=new Ds(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 Ws(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=ct(o,s[t].nodePath);null===e&&rt(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),Yt(e),U(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 Ko;return n.initializeRow(t,e),n}(n,a),d=new Ds(o);return $s(d,c),vs(d,a),ss(d,l),Ps(d,r),Ms(t.node,d),d}function Bs(t){void 0!==t.uuid&&null!==t.uuid||rt("BindingInfo.uuid is null.");const n=zt(t.uuid);n||rt(`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=ct(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===b)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==X(r))return null;if("prop"===o&&$n(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 $,policy:i,authority:i.authority})}}return{directional:e,slots:n}}(n)),null!==r)return Ws(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=ct(t,s.nodePath);if(null===e&&rt(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),Kt.has(e))continue;const r=Jt(e,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(e)}return[n,o]}(t,e),s=new Ko,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 Ds(i,s);$s(l,a.bindingSession),vs(l,a.bindingInfos);const c=[];for(const t of a.bindingInfos)t.statePathName in $&&c.push(t);return ss(l,c),Ps(l,a.nodes),Ms(t.node,l),l}const Fs=Symbol.for("wcstack.transition-runner");function zs(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 qs=new WeakSet,Us=Symbol.for("wcstack.state.view-transition-naming");function Vs(){const t=zs("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function Hs(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||qs.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.`)):(qs.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 Gs=new WeakMap,Ks=new WeakMap,Js=new WeakMap,Xs=new WeakMap;function Ys(t,e,n){!function(t,e,n){let o=Ks.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,Ks.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function Qs(t,e){Gs.set(t,e)}function Zs(t,e){let n=Js.get(t.node);void 0===n&&(n=[],Js.set(t.node,n)),n.length<1e3?n.push(e):Os(t.node,e)}function tr(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 er(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function nr(t,n,s){const r=Boolean(s);let i;const a=Ts(t.node);i=0===a.size?Bs(t):a.values().next().value;const l=e(),c=t.uuid??"",d=t.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${er(t)}`),ks(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${er(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,te(t.node),n);const e=Vs();null!==e&&Hs(i,"branch",e)}}const or=new WeakMap,sr=new WeakMap;const rr=new WeakMap;function ir(t){return rr.get(t)??[]}const ar=new Set;const lr={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 cr(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!==X(r)&&function(t,e,n){let o=or.get(t);o||(o=new Map,or.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=X(t);if(null===n)return null;const o=Q(t)?.get(n);if(void 0===o)return null;const s=tt(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&&$n(r,l)){const o=An(r,l,t.stateName,t.statePathName),i=kn(o,"to-element"),a=n?.propagationContextByBinding?.get(t)??On()??En(o);if(a.visitedEdges.has(i))null!==ne&&ne({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:i,node:r,member:l});else{const t=Mn(a,i);Rn(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:Pn++,writtenValue:n};Dn.push({receipt:i,node:t});try{return r()}finally{Dn.pop()}}(r,l,s,o,t.transactionId,e))}}else e()}if(e()){const t=lr[l];t?t(r,s):(!function(t,e,n){let o=rr.get(t);o||(o=[],rr.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,ar.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||d in c||null===X(r)||function(t,e,n){let o=sr.get(t);o||(o=new Map,sr.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 dr=new WeakSet;function ur(t){const e=t.boundPaths;if(void 0===e)return[];const n=new Set;for(const t of e){if("$"===t[0])continue;const e=t.indexOf(s);n.add(-1===e?t:t.slice(0,e))}return[...n]}function fr(t,e,n){const r=t.node,i=t.propSegments,[a,...l]=i,c=Kn(r,a);if(null===c&&rt(`State element not bound to "${a}" on web component.`),!1!==c.hasRootNode){if(0===l.length){const t=ur(c);if(0===t.length)return;return void c.createState("readonly",e=>{for(const n of t)e.$postUpdate(n)})}c.createState("readonly",t=>{t.$postUpdate(l.join(s))})}else o.debug&&console.debug(`[@wcstack/state] skipped parent→child notification for a disconnected state element on <${r.tagName.toLowerCase()}>.`,{element:r,stateProp:a,path:l.join(s)})}const hr=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),pr=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});function mr(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 gr(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 br={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing"},yr={binding:"Bound path",watch:"$watch path"};function wr(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}.${pt}`}function vr(t,e){return`$setAll("${t}") ${e}`}function Nr(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.${pt}`}const Sr=new WeakMap;function $r(t,e,n,o){if("internal"===o||void 0===e)return;if(n.startsWith("$"))return;if(!0===t.hasMappedComponentState)return;const i=G(n).segments;if("binding"===o&&i.length<2)return;if(function(t,e){let n=Sr.get(t);return void 0===n&&(n=new Set,Sr.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,n))return;const a=function(t,e,n){if(void 0!==mr(t,e))return pr;const o=G(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!==mr(t,a))return hr;if(Object(i)!==i)return hr;if(l===r){if(!Array.isArray(i)||0===i.length)return hr;i=i[0];continue}const d=mr(i,l);if(void 0===d)return{existence:"missing",missingSegment:l,candidates:gr(i,c,n)};if("function"==typeof d.get)return e===o.length-1?pr:hr;i=d.value}return pr}(e,n,t.getterPaths);"missing"===a.existence&&(console.warn(`[@wcstack/state] [${br[o]}] ${yr[o]} "${n}" does not resolve on state "${t.name}": "${a.missingSegment}" is not declared.${ht(a.missingSegment,a.candidates)} Updates to this path will be silently dropped.${pt}`),null!==ne&&ne({type:"state:path-unresolved",source:o,stateName:t.name,path:n,missingSegment:a.missingSegment}))}function Ir(t,e){const n=Ve(e);if(n.pathInfo.path in $){const t=te(e.node);return null===t&&rt(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&rt("ListIndex not found for loopContext:");const n=$[e];void 0===n&&rt(`Invalid index name: ${e}`);const o=xe(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&rt(Nr(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[ae](n)}const xr=new WeakSet;function Pr(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const _r=Object.freeze({[w]:function(t,e,n){const o=t.node,s=t.propSegments[1];"boolean"!=typeof n&&rt("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[v]:function(t,e,n){const o=t.node,s=t.propSegments[1];o.getAttribute(s)!==n&&o.setAttribute(s,n)},[N]:function(t,e,n){const o=t.propSegments[1],s=t.node.style;s[o]!==n&&(s[o]=n)},[y]:function(t,e,n){dn(n)||rt("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=es.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||rt('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=X(t);if(null===e)return null;const n=Q(t)?.get(e);return void 0===n&&rt(`Custom element <${e}> is not defined for command binding.`),tt(t)}(r);null===a&&rt(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||rt(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${ht(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),es.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 es.delete(t);const o=n[i];return"function"!=typeof o&&rt(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),es.set(t,{token:o,unsubscribe:c,elementRef:l})}}),Ar={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!dr.has(t.replaceNode)){dr.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=Ae(t),a=Ee(t),l=se(a),c=gs(eo(n.stateElement,i),l,o);n.newListValueByAbsAddress.set(a,Array.isArray(o)?o:[]);const d=Array.isArray(l)&&l.length===c.deleteIndexSet.size&&c.deleteIndexSet.size>0;if(d&&null!==t.node.parentNode){let e=Xs.get(t.node);if(void 0===e){const n=Gs.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),Xs.set(t.node,e)}if(e){const e=t.node.parentNode;e.textContent="",e.appendChild(t.node)}}let u=Ks.get(t.node),f=d?1e3-function(t){return Js.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;if(void 0!==u){for(const e of c.deleteIndexSet){const n=u.get(e);void 0!==n&&(f<=0&&n.tryDestroy()?Os(t.node,n):(ks(n),n.unmount(),Zs(t,n),f-=1),d||u.delete(e))}d&&(Ks.delete(t.node),u=void 0)}let h=t.node;const p=G(s.path+"."+r),m=n.stateElement.loopContextStack,g=bs(c);let b=null;c.newIndexes.length==c.addIndexSet.size&&c.newIndexes.length>0&&h.isConnected&&(b=document.createDocumentFragment(),Ne(b,n.rootNode));const y=e(),w=Vs(),v=t.uuid??"",N=Js.get(t.node);for(const e of c.newIndexes){let o;if(c.addIndexSet.has(e)){const r=qe(p,e);m.createLoopContext(r,r=>{if(o=void 0!==N?N.pop():void 0,void 0===o&&(o=Bs(t)),null!==b)y&&b.appendChild(document.createComment(`@@wcs-for-start:${v}:${s.path}:${e.index}`)),o.appendTo(b),y&&b.appendChild(document.createComment(`@@wcs-for-end:${v}:${s.path}:${e.index}`));else{if(h.nextSibling!==o.firstNode){if(y){const t=document.createComment(`@@wcs-for-start:${v}:${s.path}:${e.index}`);h.parentNode.insertBefore(t,h.nextSibling),h=t}o.mountAfter(h)}if(y){const t=document.createComment(`@@wcs-for-end:${v}:${s.path}:${e.index}`),n=o.lastNode??h;n.parentNode.insertBefore(t,n.nextSibling)}}As(o,r,n),null!==w&&Hs(o,"row",w)}),void 0===o&&rt(`Content not found for ListIndex: ${e.index} at path "${s.path}"`)}else{if(o=void 0!==u?u.get(e)??null:null,c.changeIndexSet.has(e)){const t=os(o);for(const e of t)Rr(e,n)}null===o&&rt(`Content not found for ListIndex: ${e.index} at path "${s.path}"`);const t=!o.mounted;if(null!==g&&g.has(e)&&tr(h,o.firstNode)||h.nextSibling===o.firstNode||o.mountAfter(h),t){const t=o,s=qe(p,e);m.createLoopContext(s,e=>{As(t,e,n)})}}h=o.lastNode||h,void 0===u&&(u=new WeakMap,Ks.set(t.node,u)),u.set(e,o)}Gs.set(t.node,h),null!==b&&(t.node.parentNode.insertBefore(b,t.node.nextSibling),Ne(b,null))},if:nr,else:nr,elseif:nr,radio:function(t,e,n){const o=t.node,s=Zo(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=Zo(o.value,t.inFilters),r=Array.isArray(n)?n:ts;o.checked=r.includes(s)}},kr=new WeakMap,Cr=new WeakMap,Er=new WeakMap;function Mr(){}function Tr(t){const e=t.replaceNode,n=t.propSegments[0];return function(t,e){return!0===Yo.get(t)?.has(e)}(e,n)?fr:1===t.propSegments.length&&function(t,e){return!0===Qo.get(t)?.has(e)}(e,n)?Mr:cr}function Or(t,e){const n=Zo(Ir(e.state,t),t.outFilters);if(!0===Cr.get(t))return void e.deferredSelectBindings.push({binding:t,value:n});let o=kr.get(t);if(void 0===o){if(kr.has(t))return o=Tr(t),o===fr&&kr.set(t,o),void o(t,e,n);if(o=Ar[t.bindingType],void 0===o){const e=t.propSegments[0];if(o=_r[e],kr.set(t,o),void 0===o){X(t.replaceNode)?(o=Tr(t),o===fr&&kr.set(t,o)):(o=cr,kr.set(t,o))}}if(o===cr){if("SELECT"===t.node.tagName){const o=t.propSegments[0];if("value"===o||"selectedIndex"===o)return e.deferredSelectBindings.push({binding:t,value:n}),void Cr.set(t,!0)}}o(t,e,n)}else o(t,e,n)}function Rr(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=Ee(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!==Er.get(t)){const e=X(t.replaceNode);if(e&&void 0===Q(t.replaceNode)?.get(e))return void function(t,e){if(xr.has(t))return;xr.add(t);const n=()=>{xr.delete(t);const e=Xo(t);(null===e||e.shouldApplyState(t))&&Lr([t])},o=n=>{xr.delete(t),Pr(e,n)},s=Xo(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{xr.delete(t),r()})||(xr.delete(t),r()))}const r=Q(t.replaceNode);if(null===r)return xr.delete(t),void Pr(e,new Error("CustomElementRegistry is unavailable."));Io(r).wait(e,()=>{t.replaceNode.isConnected?n():xr.delete(t)},o)}(t,e);Er.set(t,!0)}if(!0===e.sameRootVerified&&t.stateName===e.stateName)return void Or(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Se(o),null===o&&rt("Root node for fragment not found for binding.")),t.stateName!==e.stateName||o!==e.rootNode){const n=Ti(o,t.stateName);null===n&&rt(`State element with name "${t.stateName}" not found for binding.`),n.createState("readonly",s=>{const r={stateName:t.stateName,rootNode:o,stateElement:n,state:s,appliedBindingSet:e.appliedBindingSet,newListValueByAbsAddress:e.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:e.updatedAbsAddressSetByStateElement,deferredSelectBindings:e.deferredSelectBindings};Or(t,r)})}else Or(t,e)}function Dr(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!==ne&&ne({type:"state:binding-apply-error",stateName:t.stateName,path:t.statePathName,bindingType:t.bindingType,error:e})}function Lr(t,e){let n=0;const s=new Set,r=new Map,i=new Map,a=[];for(;n<t.length;){let l=t[n];const c=l.stateName;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 d=l.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=Se(d),null===d&&rt("Root node for fragment not found for binding."));const u=Ti(d,c);null===u&&rt(`State element with name "${c}" not found for binding.`),u.createState("readonly",o=>{const f={rootNode:d,stateName:c,stateElement:u,state:o,appliedBindingSet:s,newListValueByAbsAddress:r,updatedAbsAddressSetByStateElement:i,deferredSelectBindings:a,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{Rr(l,f)}catch(t){Dr(l,t)}n++;const e=t[n];if(!e)break;const o=e.replaceNode.getRootNode();if(e.stateName!==c||o!==f.rootNode)break;l=e}})}for(const{binding:t,value:n}of a)try{cr(t,{propagationContextByBinding:e},n)}catch(e){Dr(t,e)}for(const[t,e]of r.entries())re(t,e);for(const[t,e]of i.entries())t.createState("writable",t=>{t[fe](Array.from(e))})}function jr(t,e){const[n,o,s]=Xt(t),r=Jo(t);for(const t of n)ee(t,e);Lr(r.initialize(o)),function(t,e,n){for(const o of t)n.deferUntilDefined(o.node,o.tagName,()=>{const t=Qt(o);0!==t.length&&(ee(o.node,e),Lr(n.initialize(t)))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,t)})}(s,e,r)}const Wr=/\{\{\s*(.+?)\s*\}\}/g,Br=new Set(["SCRIPT","STYLE"]);function Fr(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&&Br.has(t.parentElement.tagName)||zr(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),Fr(e.content)}else Fr(t.content)}function zr(t){const e=t.data;if(Wr.lastIndex=0,!Wr.test(e))return;Wr.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=Wr.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 Ur(){if(qr)return qr;const t=[],e=It("not",t)(St);return qr={filterName:"not",args:t,filterFn:e},qr}const Vr=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Hr(t,e){const n=e+s+r,o=t.indexOf("|"),i=t.indexOf("@");let a,l;if(-1!==o?(a=t.slice(0,o).trim(),l=t.slice(o)):-1!==i?(a=t.slice(0,i).trim(),l=t.slice(i)):(a=t.trim(),l=""),"."===a)a=n;else{if(!a.startsWith("."))return t;a=n+s+a.slice(1)}return l.length>0?a+l:a}function Gr(t,e){const n=Vr.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+Hr(s,e)+r}function Kr(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=Hr(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function Jr(t,e){return Kr(t,e)}function Xr(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=Gr(n.data,e);continue}const o=t;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const t=Kr(r,e);t!==r&&o.setAttribute(n,t)}}}function Yr(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 Qr(t){const e=[],n=Gt(t);for(const t of n){const n=qt(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:Yr(o),parseBindTextResults:n})}return e}function Zr(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 ti=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),ei=Ur();function ni(t,e){const n=e.outFilters;return{...e,outFilters:[...n,ei],bindingType:t}}function oi(t,e,n,o){Zr(e),"string"==typeof o&&Xr(e,o),si(t,e,o);return{fragment:e,parseBindTextResult:n,nodeInfos:Qr(e)}}function si(t,e,n){const s=o.commentElsePrefix,r=Vt(e),i=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode(t){const e=t;if(r.length>0&&-1!==r.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 a=null;const l=[],c=[];for(;i.nextNode();){const t=i.currentNode;c.push(t)}for(const e of c){let r=e.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(r=Jr(r,n));let i=Ot(r)[0];const c=ti.get(i.bindingType);if(void 0===c)continue;const d=i.bindingType,u=e.content,f=is();let h=null;const p="for"===d?i.statePathName:n;if("else"===d){null===a&&rt("'else' binding found without preceding 'if' or 'elseif' binding."),i=ni("else",a.parseBindTextResult),h=oi(t,u,i,p),Ft(f,t,h);const n=l.at(-1),o=document.createComment(`@@${c}:${f}`);void 0!==n?(e.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:Yr(o),parseBindTextResults:qt(o)})):e.replaceWith(o)}else if("elseif"===d){null===a&&rt("'elseif' binding found without preceding 'if' or 'elseif' binding."),h=oi(t,u,i,p),Ft(f,t,h);const n=document.createComment(`@@${c}:${f}`),o=is(),r={fragment:document.createDocumentFragment(),parseBindTextResult:ni("else",a.parseBindTextResult),nodeInfos:[]};r.fragment.appendChild(n),r.nodeInfos.push({nodePath:Yr(n),parseBindTextResults:qt(n)}),Ft(o,t,r);const d=l.at(-1);l.push(r);const m=document.createComment(`@@${s}:${o}`);void 0!==d?(e.remove(),d.fragment.appendChild(m),d.nodeInfos.push({nodePath:Yr(m),parseBindTextResults:qt(m)})):e.replaceWith(m)}else{h=oi(t,u,i,p),Ft(f,t,h);const n=document.createComment(`@@${c}:${f}`);e.replaceWith(n)}"if"===d?(l.length=0,a=h):"elseif"===d?a=h:"else"===d&&(a=null,l.length=0)}}async function ri(t){const e=t.querySelectorAll(o.tagNames.state),n=[],s=Q(t);null===s&&rt(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const t of e){if(Ut(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function ii(t){if(t===document)await ri(document),Fr(document),si(document,document),jr(document.body,null);else{const e=t;e.host.hasAttribute(o.bindAttributeName)&&await q(e.host),await ri(e),Fr(e),si(e,e),jr(e,null)}}const ai="1.33.0",li="undefined"==typeof HTMLElement?class{}:HTMLElement,ci=/^@@wcs-(?:for|if|elseif|else):[^-]/,di=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,ui=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,fi=/^@@wcs-text-start:(.+)$/;function hi(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class pi extends li{_stateData=null;_templates=null;_hydrateProps=null;get name(){return this.getAttribute("name")||"default"}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=ai.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 findByName(t,e){const n=o.tagNames.ssr,s=t instanceof Element?t:t instanceof Document?t.documentElement:null;if(!s)return null;return s.querySelector(`${n}[name="${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=hi(JSON.stringify(e)),t.appendChild(n);const s=Array.from(Bt.keys());for(const e of s){const n=zt(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(ar);if(r.length>0){const e={};for(let t=0;t<r.length;t++){const n=r[t],o=ir(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=hi(JSON.stringify(e)),t.appendChild(n)}}ar.clear()}static removeBlockBoundaryComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;(di.test(t.data)||ui.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;ci.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=fi.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;di.test(t.data)&&i.push(t)}for(const t of i){const e=di.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()}pi.restoreTextBindings(e);const a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const t=a.currentNode;if(ci.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 mi=new Set(["for","if","elseif","else"]);function gi(t){const e=new Ko;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]=Xt(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 bi(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 yi(t,e){const n=t;let s=null;for(const[t,r]of e.templates){let e=Ot(r.getAttribute(o.bindAttributeName)||"")[0];const i=e.bindingType;"else"===i&&s?e={...s,outFilters:[...s.outFilters,Ur()],bindingType:"else"}:"elseif"===i&&s&&(e={...e,stateName:s.stateName}),"if"===i||"elseif"===i?s=e:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?e.statePathName:void 0;Zr(a),"string"==typeof l&&Xr(a,l),si(n,a,l);Ft(t,n,{fragment:a,parseBindTextResult:e,nodeInfos:Qr(a)})}}async function wi(t){await ri(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="${ai}". Falling back to full render.`),pi.cleanupDom(t),!1}for(const n of e)yi(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=di.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=js(o.nodes),{bindingInfos:s,subscriberNodes:i,bindingSession:a}=gi(o.nodes);$s(e,a);for(const t of i)t.nodeType===Node.ELEMENT_NODE&&t.setAttribute("data-wcs-completed","");vs(e,s),Ps(e,i);const l=[];for(const t of s)t.statePathName in $&&l.push(t);if(ss(e,l),"for"===o.type&&null!==o.index){const i=bi(t,"for",o.uuid);if(i){const t=cs(null,o.index);Ys(i,t,e),Qs(i,o.nodes[o.nodes.length-1]),Ms(i,e),_s(e,qe(G(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=bi(t,o.type,o.uuid);n&&(Ms(n,e),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}))}}for(const[e,o]of n){const n=bi(t,"for",e);if(!n)continue;const s=n.getRootNode(),r=zt(e);if(!r)continue;const i=r.parseBindTextResult.stateName,a=r.parseBindTextResult.statePathName,l=Ti(s,i);l&&l.createState("readonly",t=>{const e=t[a];Array.isArray(e)&&fs(e,o)})}}(document.body,n),pi.removeBlockBoundaryComments(document.body);const s=[];for(const t of e)t.parentNode&&(s.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());pi.restoreTextBindings(document.body);const[i,a]=Xt(document.body);for(const t of i)if(t.nodeType===Node.ELEMENT_NODE){const e=t;e.hasAttribute("data-wcs-completed")||(ee(t,null),e.setAttribute("data-wcs-completed",""))}else ee(t,null);const l=[],c=[],d=Jo(document.body).initialize(a);for(const t of d)if("event"!==t.bindingType)if(mi.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=Ee(t),n=Ti(t.replaceNode.getRootNode(),t.stateName);n&&n.createState("readonly",n=>{const o=n[t.statePathName];Array.isArray(o)&&re(e,o)})}Lr(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 vi=Symbol.for("wcstack.binder");const Ni=Symbol.for("wcstack.binder.pending"),Si=Symbol.for("wcstack.binder.taken");function $i(){const t=function(){const t=globalThis[vi];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[Ni];return void 0===e&&(e=[],t[Ni]=e),e}();if(0===e.length)return;const n=e.splice(0,e.length),o=function(){const t=globalThis;let e=t[Si];return void 0===e&&(e=new WeakSet,t[Si]=e),e}();for(const e of n)o.add(e),t.bind(e)}function Ii(t){if(Wo(t))return!0;if(!xi(t))return!1;if(t.hasAttribute(o.bindAttributeName))return!1;const e=t.querySelector(`[${o.bindAttributeName}]`);return null!==e&&Wo(e)}function xi(t){return 1===t.nodeType}function Pi(t){if(Ii(t))return;Fr(t),si(t.getRootNode(),t);const e=t.hasAttribute(o.bindAttributeName),n=t.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);jr(e&&s?n:t,null)}const _i=[];function Ai(){const t=_i.splice(0,_i.length);for(const e of t)Pi(e);$i()}const ki={protocol:"wcs-binder",version:1,bind:function(t){var e;xi(t)&&!Ii(t)&&(e=t.getRootNode(),Ri.has(e)?Pi(t):_i.push(t))}};const Ci=new WeakMap,Ei=new WeakMap,Mi=new Set;function Ti(t,e){let n=Ci.get(t);return n&&n.get(e)||null}function Oi(t){return Ei.get(t)??Promise.resolve()}const Ri=new WeakSet;function Di(t){Ri.add(t)}function Li(t,n,s){let r=Ci.get(t);if(null===s){if(!r)return;const e=r.get(n);r.delete(n),0===r.size&&Ci.delete(t),void 0!==e&&(Mi.delete(e),null!==ne&&ne({type:"state:element-unregistered",name:n,rootNode:t,element:e})),o.debug&&console.debug(`State element unregistered: name="${n}"`)}else{if(!r){r=new Map,Ci.set(t,r);const n=!e()&&s.hasAttribute?.("enable-ssr");if("HTMLDocument"===t.constructor.name||"Document"===t.constructor.name){const e=new Promise((e,o)=>{queueMicrotask(async()=>{try{if(n){await wi(t)||await ii(t)}else await ii(t);Di(t),Ai(),e()}catch(t){o(t)}})});Ei.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await ii(t),Di(t),Ai(),e()}catch(t){n(t)}})});Ei.set(t,e)}}r.has(n)&&rt(`State element with name "${n}" is already registered.`),r.set(n,s),Mi.add(s),null!==ne&&ne({type:"state:element-registered",name:n,rootNode:t,element:s}),o.debug&&console.debug(`State element registered: name="${n}"`,s)}}let ji=0,Wi=0;const Bi=[];function Fi(t,e=0){const n=Bi.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?Bi.push(o):Bi.splice(n,0,o)}function zi(t){queueMicrotask(()=>{throw t})}const qi=new class{_queueUpdateRecords=[];constructor(){}enqueueAbsoluteAddress(t,e=null){ji>Wi&&(Wi=ji);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!==ne&&null!=t&&null!==e.context&&t.transactionId!==e.context.transactionId&&ne({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,stateName:t.absolutePathInfo.stateName,transactionId:e.transactionId,hop:e.hop,maxHops:32}),null!==ne&&ne({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop});continue}const n=We(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?Lr(o,s):Lr(o)};if(e()||0===o.length)t();else{const e=function(t,e,n){const o=zs(t);if(null!==o)return o.run(e,{source:t,types:n});e()}("state",t);void 0!==e&&e.catch(zi)}}finally{!function(t){for(const e of Bi.slice())e.listener(t)}(new Set(n.keys()))}}};function Ui(){return qi}const Vi=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Hi(t,e,n,o){return{node:t,propName:e.propName,statePathName:e.statePathName,stateName:e.stateName,bindingType:e.bindingType,inFilters:e.inFilters,outFilters:e.outFilters,origin:n,raw:o}}const Gi="__WCSTACK_DEVTOOLS_HOOK__";function Ki(){const t=globalThis,e=t[Gi];if(void 0!==e)return 1!==e.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${e.version}, expected 1. 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:1,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[Gi]=n,n}const Ji=t=>{null!==ne&&ne({type:"state:update-batch",addresses:t})};function Xi(t){const e=null!==ne;!function(t){ne=t}(t);const n=null!==t;n&&!e?Fi(Ji,0):!n&&e&&function(t){const e=Bi.findIndex(e=>e.listener===t);-1!==e&&Bi.splice(e,1)}(Ji)}function Yi(t){return{name:t.name,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 Qi(t,e){return Ti(e,t)??rt(`devtools: state element not found: name="${t}"`)}let Zi=null;function ta(){if(e())return;if(null!==Zi)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:ai,getStateElements(){const t=[];for(const e of Mi)t.push(Yi(e));return t},keys(t,e){const n=Qi(t,e),o=[];return n.createState("readonly",t=>{for(const e of Object.keys(t))if(!e.includes("*")&&!e.startsWith("$")){try{if("function"==typeof t[e])continue}catch{}o.push(e)}}),o},read(t,e,n,o){let s;return Qi(t,e).createState("readonly",t=>{s=t.$resolve(n,o??[])}),s},write(t,e,n,o,s){Qi(t,e).createState("writable",t=>{void 0!==s&&s.length>0?t.$resolve(n,s,o):t[n]=o})},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.stateName,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=zt(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(Hi(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=lt(e,Ot(n));for(const o of t)r(Hi(e,o,"attribute",n))}catch{}continue}const e=Vi.exec(t.data.trim());if(null===e)continue;const n=e[1]||o.commentTextPrefix,s=e[2],a=zt(s);if(null===a){if(n===o.commentTextPrefix)try{r(Hi(t,Wt(s),"comment",s))}catch{}}else r(Hi(t,a.parseBindTextResult,"comment",s)),i(s)}return e}(t),_setSink:Xi};Zi=t,Ki().register(t)}const ea={protocol:"wcs-ssr-snapshot",version:1,build:function(t){const e=o.tagNames.state,n=o.tagNames.ssr,s=t.querySelectorAll(`${e}[enable-ssr]`);for(const t of s){const e=t.getAttribute("name")||"default",o=t.previousElementSibling;if(null!==o&&o.tagName.toLowerCase()===n&&(o.getAttribute("name")||"default")===e)continue;const s=document.createElement(n);s.setAttribute("name",e),s.setAttribute("version",ai),pi.buildContent(s,pi.extractStateData(t)),t.parentNode?.insertBefore(s,t)}}};const na="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let oa=0;async function sa(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++oa}\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 ${na}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${na}`}(e,t,s),{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function ra(t){try{const e=await import(function(t){return new URL(t,document.baseURI).href}(t));return e.default||{}}catch(t){rt(`Failed to load script file: ${t}`)}}class ia{_loopContextStack=Array(i).fill(void 0);_length=0;_getBaseDepth;constructor(t){this._getBaseDepth=t}createLoopContext(t,e){null===t.listIndex&&rt("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=i&&rt("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&&rt("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&&rt("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else if(n.listIndex.length!==n.pathInfo.wildcardCount){const t=this._getBaseDepth();n.listIndex.length!==n.pathInfo.wildcardCount+t&&rt(`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}, base depth ${t}).`)}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 aa=new WeakMap;function la(t,e){let n=aa.get(t);void 0===n&&(n=new Map,aa.set(t,n));let o=n.get(e);return void 0===o&&(o=new cn(e,t.name),n.set(e,o)),o}const ca=new WeakMap;function da(t){const e=ca.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 la(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:la(t,n)}},set(){rt("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){rt("$command namespace is read-only; deleting from it is not allowed.")}});return ca.set(t,n),n}const ua=Symbol("wcs-stream-last-notified-uncertain"),fa=new WeakMap;function ha(t,e){const n=fa.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function pa(t,e){const n=fa.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:ua,error:Object.is(o.error,null)?null:ua})}const ma=new Set;function ga(t){ma.delete(t)}const ba=new WeakMap;function ya(t){return ba.get(t)??new Map}function wa(t){ga(t);const e=ba.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,pa(t,n.name)}const va=(t,e)=>e,Na=new Set;function Sa(t,e){const n=e[O];if(void 0===n)return void ha(t,Na);"object"==typeof n&&null!==n||rt(`${O} 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&&rt(`${O} entry name must be a non-empty string.`),i.includes(s)&&rt(`${O} entry "${i}" must be a flat property name ("${s}" is not allowed).`),i.includes(r)&&rt(`${O} entry "${i}" must be a flat property name ("${r}" is not allowed).`),i.startsWith("$")&&rt(`${O} entry "${i}" must not start with "$" (reserved namespace).`),i in Object.prototype&&rt(`${O} entry "${i}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(i)&&rt(`${O} entry "${i}" conflicts with a getter declared on the state.`),t.setterPaths.has(i)&&rt(`${O} entry "${i}" conflicts with a setter declared on the state.`),"object"==typeof a&&null!==a||rt(`${O} entry "${i}" must be an object ({ args?, source, fold?, initial? }).`);const n=a;"function"!=typeof n.source&&rt(`${O} entry "${i}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&rt(`${O} entry "${i}" fold must be a function.`),l&&!("initial"in n)&&rt(`${O} entry "${i}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&rt(`${O} entry "${i}" args must be a function.`);const c={name:i,definition:{args:n.args??null,source:n.source,fold:n.fold??va,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){ba.set(t,e)}(t,o),ha(t,new Set(o.keys()))}const $a=new WeakMap,Ia=new WeakMap;function xa(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=ya(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&ya(t).has(n),ownKeys:()=>Array.from(ya(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=ya(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){rt(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){rt(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function Pa(t){const e=$a.get(t);if(void 0!==e)return e;const n=xa(t,L,t=>t.status);return $a.set(t,n),n}function _a(t){const e=Ia.get(t);if(void 0!==e)return e;const n=xa(t,j,t=>t.error);return Ia.set(t,n),n}function Aa(t){$a.delete(t),Ia.delete(t)}let ka=null;async function Ca(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 Ea(t){const e=ya(t);if(0!==e.size){!function(t){ma.add(t)}(t);for(const n of e.values())Ma(t,n)}}function Ma(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=ka,r=new Set;let i;ka=r;try{t.createState("readonly",t=>{i=n(t)})}finally{ka=o}i instanceof Promise&&rt(`${O} entry "${e.name}" args must be synchronous (it returned a Promise).`);const a=`${L}${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||rt(`${O} 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&&rt(`${O} 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}),Ta(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(){Ta(t,e,"done",null)},fail(o){Ta(t,e,"error",o),n.abort()}};Ca(r.source,o,n.signal,i)}function Ta(t,e,n,o){e.status=n,e.error=o;const r=function(t,e){return fa.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=fa.get(t);void 0===s&&(s=new Map,fa.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{i&&t.$postUpdate(`${L}${s}${e.name}`),a&&t.$postUpdate(`${j}${s}${e.name}`)}))}Fi(function(t){const e=ma;if(0===e.size)return;const n=[];for(const o of e)for(const e of ya(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)&&ya(t).get(o.name)===o)try{Ma(t,o)}catch(n){o.controller?.abort(),e.has(t)&&ya(t).get(o.name)===o&&Ta(t,o,"error",n)}},20);const Oa=new WeakMap,Ra=new Set,Da=new Map;function La(t){return Oa.get(t)??Da}function ja(){return Ra}function Wa(t,e){const n=e[R];if(void 0===n)return null;"object"==typeof n&&null!==n||rt(`[wcs/watch-declaration-invalid] ${R} must be an object mapping state paths to handler functions.${pt}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&rt(`[wcs/watch-declaration-invalid] ${R} entry "${e}" must be a function.${pt}`),0===e.length&&rt(`[wcs/watch-declaration-invalid] ${R} entry name must be a non-empty state path.`),e.startsWith("$")&&rt(`[wcs/watch-declaration-invalid] ${R} entry "${e}" must not start with "$" (reserved namespace).${pt}`),e.includes(a)&&rt(`[wcs/watch-declaration-invalid] ${R} entry "${e}" must not target another state ("${a}" is not allowed); watch only paths of its own state.${pt}`),e in Object.prototype&&rt(`[wcs/watch-declaration-invalid] ${R} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const n=G(e);for(const t of n.segments)0===t.length&&rt(`[wcs/watch-declaration-invalid] ${R} entry "${e}" has an empty path segment.${pt}`);n.wildcardCount>128&&rt(`[wcs/watch-declaration-invalid] ${R} entry "${e}" exceeds the maximum wildcard depth (128).`),o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){Oa.set(t,e)}(t,o),s.size>0?s:null}const Ba=new WeakMap;function Fa(t,e,n){let o=Ba.get(t);void 0===o&&(o=new Map,Ba.set(t,o)),o.set(e,n)}const za=new Map;function qa(t){0!==La(t).size&&(function(t){Ra.add(t)}(t),function(t){const e=[];for(const n of La(t).values())Va(t,n)&&e.push(n);if(0===e.length)return;t.createState("readonly",n=>{for(const o of e)try{Fa(t,Ua(t,o),n[o.path])}catch(e){Ga(t,o.path,"prime",e)}})}(t))}function Ua(t,e){return we(pe(t,e.pathInfo),null)}function Va(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const Ha={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Ga(t,e,n,o){console.error(`[@wcstack/state] $watch ${Ha[n]} "${e}" threw.`,o),null!==ne&&ne({type:"state:watch-error",phase:n,stateName:t.name,path:e,error:o})}function Ka(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 Ja(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=Va(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 Ga(e,n.path,"evaluate",t)}const a=r?function(t,e){return Ba.get(t)?.get(e)}(e,o):function(t){return za.get(t)}(o);r&&Fa(e,o,i),null!==ne&&ne({type:"state:watch-fired",stateName:e.name,path:n.path}),n.handler.call(t,i,a,...s)})}catch(t){Ga(e,n.path,"handler",t)}}function Xa(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 Ya(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 Qa(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 Za(t){return t.startsWith("$")}function tl(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 el(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 nl(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||rt(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||rt(`${e} entries must be non-empty strings.`),t.startsWith("$")&&rt(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&rt(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}function ol(t){const e=nl(t,A)??[],n=nl(t,k)??[],o=tl(t),s=function(t){const e=t[O];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}rt(`${A} entry "${t}" is not declared on the state.${ht(t,el(o,"value"))}`)}"function"==typeof e.value&&rt(`${A} entry "${t}" is a method. Declare it in ${k} instead.`)}for(const t of n){const e=o[t];void 0===e&&rt(`${k} entry "${t}" is not declared on the state.${ht(t,el(o,"method"))}`),"function"!=typeof e.value&&rt(`${k} entry "${t}" is not a method. Declare it in ${A} instead.`)}return{bindables:e,commands:n,streamBackedBindables:r}}Fi(function(t){const e=ja();try{if(0===e.size)return;const n=function(){const t=Wi;return Wi=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!==ne&&ne({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=La(t).get(n.absolutePathInfo.pathInfo.path);if(void 0===s)continue;let r=[];if(s.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;r=Pe(n.listIndex,s.pathInfo.wildcardCount)}o.push({stateElement:t,entry:s,absAddress:n,indexes:r})}if(0===o.length)return;o.sort(Ka),function(t){ji=t+1}(n);try{for(const t of o)e.has(t.stateElement)&&La(t.stateElement).get(t.entry.path)===t.entry&&Ja(t)}finally{ji=0}}finally{za.clear()}},10);const sl=new Map;class rl{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=G(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 il(t){let e;return sl.get(t)??(sl.set(t,e=new rl(t)),e)}function al(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[e];return void 0===o||null===n.listIndex?null:xe(n.listIndex,o,n.pathInfo.wildcardCount)}const ll=new WeakMap;function cl(t,e){null===e?ll.delete(t):ll.set(t,e)}function dl(t){const e=ll.get(t);e&&(e.dirty=!0)}const ul=[],fl=[];let hl=0;function pl(t,e){ul[hl]=t,fl[hl]=e,hl++}function ml(){hl--,ul[hl]=void 0,fl[hl]=void 0}function gl(t,e){return!0!==t.hasMappedComponentState&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function bl(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 yl(t,e,n,o,s){const i=e.pathInfo.segments[0];if(i===E)return bl(da(s),e.pathInfo.segments);if(i===L)return bl(Pa(s),e.pathInfo.segments);if(i===j)return bl(_a(s),e.pathInfo.segments);if(!(e.pathInfo.path in t)){const i=e.parentAddress??rt(function(t,e,n,o){return`[${br.binding}] Path "${e}" does not exist on state "${t}".${ht(e,gr(n,"",o))}${pt}`}(s.name,e.pathInfo.path,t,s.getterPaths)),a=vl(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??rt(Nr(`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)){o.pushAddress(e);try{return Reflect.get(t,e.pathInfo.path,n)}finally{o.popAddress()}}else{if(!0!==s.hasMappedComponentState)return Reflect.get(t,e.pathInfo.path);pl(s,e);try{return Reflect.get(t,e.pathInfo.path)}finally{ml()}}}function wl(t,e,n,o,s){const r=we(pe(s,e.pathInfo),e.listIndex),i=function(t){return ll.get(t)??null}(r);if(null!==i&&!1===i.dirty)return i.value;const a=yl(t,e,n,o,s);return cl(r,{value:a,dirty:!1}),a}function vl(t,e,n,o){!function(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=Ie(e.pathInfo,o);if(t>0){let r=!1;const i=e.listIndex??null,a=n.listIndex??null;for(let n=0;n<t;n++)if((null!==i?xe(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?xe(a,n,o.wildcardCount):null)){r=!0;break}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}(o,e),function(t,e){if(null===ka)return;const n=pe(t,e.pathInfo);ka.add(we(n,e.listIndex))}(o.stateElement,e);const s=o.stateElement;return gl(s,e)?wl(t,e,n,o,s):yl(t,e,n,o,s)}const Nl=new WeakMap;function Sl(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=qe(f,r),p=Nl.get(h),m=vl(t,h,e,n),g=gs(eo(n.stateElement,r),p,m).newIndexes,b=l[c]??null;if(i.set(h,m),null===b)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[b]??rt(`ListIndex not found at index ${b} 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())Nl.set(t,e);return l}function $l(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=us(vl(t,qe(a,r),e,n));null==l&&rt(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??rt(`ListIndex not found at index ${c} of ${a.path}`)}return r}function Il(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 xl(t,e,n,o){"object"==typeof t&&null!==t||rt(`${D} 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&&rt(`${D} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function Pl(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&rt(`${D} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function _l(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];xl(a,n,o,i);const l=Pl(a,e,n,o,i);r.has(l)&&rt(`${D} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Al(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 kl(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const i=vl(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 Cl=new WeakMap;function El(t,e){null===e?Cl.delete(t):Cl.set(t,e)}function Ml(t,e,n){const s=G(t.wildcardParentPaths[e]),r=pe(t.stateElement,s),i=qe(s,n),a=se(we(r,n)),l=t.stateProxy[ae](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}`),[]}}(gs(eo(t.stateElement,i.listIndex),a,l),t.searchType);if(e===t.wildcardPaths.length-1)t.targetListIndexes.push(...c);else for(const n of c)Ml(t,e+1,n)}const Tl=[];function Ol(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:Tl,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:Tl,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Rl=[];function Dl(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Rl;let r=null;const i=e+s;for(const t of o){if(t!==e&&!t.startsWith(i))continue;const o=G(t);if(o.wildcardCount!==n.wildcardCount)return null;(r??=[]).push(o)}return r??Rl}function Ll(t,e,n){const o=e.pathInfo.path,s=t.staticMap.get(o);if(s)for(const i of s){const s=G(i);if(t.listPathSet.has(o)&&s.lastSegment===r){const r=t.stateProxy[ae](e),a=se(we(pe(t.stateElement,e.pathInfo),e.listIndex)),l=Ol(t,o,0,0,gs(eo(t.stateElement,e.listIndex),a,r));for(const e of l.fullRows){const o=qe(s,e);t.result.add(o),n.push(o)}if(null!==l.movedRows){const e=Dl(t,i,s);if(null===e)for(const e of l.movedRows){const o=qe(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=qe(s,o);t.result.add(e),n.push(e)}}}else{const o=qe(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=G(o),r=[];if(s.wildcardCount>0){const n=Ie(e.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&rt(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=xe(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const i={stateName:t.stateName,stateElement:t.stateElement,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};Ml(i,n,o),r.push(...i.targetListIndexes)}else{null===e.listIndex&&rt(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=xe(e.listIndex,n-1,e.pathInfo.wildcardCount);r.push(t)}}else r.push(null);for(const e of r){const o=qe(s,e);t.result.add(o),n.push(o)}}}function jl(t,e,n,o,s,r,i,a,l,c){const d=n.pathInfo.path;if(!o.has(d)&&!s.has(d))return l(n),[];const u=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&&rt(`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}(d,o,s,1e3),f={ranks:u,stateName:t,stateElement:e,staticMap:o,dynamicMap:s,result:new Set,listPathSet:r,visited:new Set,stateProxy:i,searchType:a,listExpansion:c?.listExpansion??"full",keyedMergePath:c?.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,Ll(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}(f,n,l),Array.from(f.result)}function Wl(t,e,n,o,s){const r=t.watchPaths;null!=r&&s&&r.has(e)&&function(t,e){za.has(t)||za.set(t,e)}(n,o)}function Bl(t,e,n,s,r){const i=o.enablePropagationContext?On()??En(-1):null,a=Ui();a.enqueueAbsoluteAddress(e,i),jl(s.stateName,s.stateElement,t,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",e=>{if(e===t)return;const n=we(pe(s.stateElement,e.pathInfo),e.listIndex);dl(n),a.enqueueAbsoluteAddress(n,i)},{listExpansion:"diff",keyedMergePath:r})}function Fl(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=vl(t,n,s,i),l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(l===r){const t=e.listIndex?.index??rt(Nr(`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)){i.pushAddress(e),i.beginUntrack();try{return Reflect.set(t,e.pathInfo.path,o,s)}finally{i.endUntrack(),i.popAddress()}}else{if(!0!==i.stateElement.hasMappedComponentState)return Reflect.set(t,e.pathInfo.path,o);pl(i.stateElement,e);try{return Reflect.set(t,e.pathInfo.path,o)}finally{ml()}}}finally{Bl(e,n,s,i,a)}}function zl(t,e,n,o,s,r,i){let a=e.parentAddress??rt(`address.parentAddress is undefined path: ${e.pathInfo.path}`),l=function(t){return Cl.get(t)??null}(a);if(null===l){const e=vl(t,a,s,r)??[],n=us(e)??[];l={value:[...e],listIndexes:[...n]},El(a,l)}try{return Fl(t,e,n,o,s,r,i)}finally{const n=l.value.indexOf(o),i=vl(t,a,s,r)??[],c=Array.isArray(i)?us(i)??[]:[],d=e.listIndex.index,u=-1!==n?l.listIndexes[n]:cs(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;El(a,null)}}}function ql(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=vl(t,e,o,i),c=function(t,e,n,o){const s=_l(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=_l(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=eo(a.stateElement,e.listIndex);null===us(o)&&gs(c,null,o);const d=gs(c,o,n.list),u=Ul(t,e,n.list,i,a,l),f=G(l+s+r);for(const e of n.matched){const n=Al(e.oldRow,e.newRow);if(0===n.length)continue;const o=d.newIndexes[e.position];for(const r of n)void 0!==o?ql(t,qe(G(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 Ul(t,e,n,o,i,null)}function Ul(t,e,n,s,i,a){const l=i.stateElement,c=e.pathInfo.path,d=!!Ln&&(Ln=!1,!0);if(!(c in t)&&null!==e.parentAddress&&!l.elementPaths.has(c)){const u=vl(t,e.parentAddress,s,i);if("object"==typeof u&&null!==u){const t=e.pathInfo.lastSegment,f=t===r?e.listIndex?.index:t;let h,p=!1;if(!d&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const t=void 0!==f&&f in u,e=void 0!==f?u[f]:void 0;if(t&&Object.is(e,n))return!0;h=e,p=!0}const m=gl(l,e),g=we(pe(l,e.pathInfo),e.listIndex);null!==ne&&ne({type:"state:write",absoluteAddress:g,value:n,oldValue:h,hasOldValue:p}),Wl(l,c,g,h,p);try{return void 0===f&&rt(Nr(`path "${c}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),Reflect.set(u,f,n)}finally{Bl(e,g,s,i,a),m&&cl(g,{value:n,dirty:!1}),Il(l,e.pathInfo,{value:n})}}}let u,f=!1;if(!d&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=vl(t,e,s,i);if(kl(t,e,s,i)&&Object.is(o,n))return!0;u=o,f=!0}const h=l.elementPaths.has(e.pathInfo.path),p=gl(l,e),m=we(pe(l,e.pathInfo),e.listIndex);null!==ne&&ne({type:"state:write",absoluteAddress:m,value:n,oldValue:u,hasOldValue:f}),Wl(l,c,m,u,f);try{return h?zl(t,e,m,n,s,i,a):Fl(t,e,m,n,s,i,a)}finally{p&&cl(m,{value:n,dirty:!1}),Il(l,e.pathInfo,{value:n})}}function Vl(t,e,n,o){return(e,s,r)=>{const i=G(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&&rt(wr("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=qe(i,$l(t,n,o,i,s));if(!(void 0!==r))return vl(t,a,n,o);ql(t,a,r,n,o)}}function Hl(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return al(o,s.wildcardPaths.at(-1)??rt(`lastWildcardPath is null: ${e.pathInfo.path}`))??rt(`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]??rt(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=us(vl(t,qe(i,s),n,o))??rt(`ListIndex not found: ${i.path}`),l=e.wildcardIndexes[r]??rt(`wildcardIndex is null: ${e.pathInfo.path}`);s=a[l]??rt(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":rt(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}const Gl=`${L}${s}`,Kl=`${j}${s}`,Jl=new WeakMap;function Xl(t,e,n,o){const s=$[e];if(void 0!==s){0===o.addressStackLength&&rt(`No active state reference to get list index for "${e.toString()}".`);const t=o.lastAddressStack,n=t?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const r=t?.listIndex;null==r&&rt(`ListIndex not found: ${e.toString()}`);const i=xe(r,s,t.pathInfo.wildcardCount);return i?.index??rt(`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=Vl(t,0,n,o);return(e,r)=>{const i=G(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&&rt(wr("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=al(o,i.wildcardPaths[t]);if(e){r=Pe(e,e.length-Zn(o.stateElement));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-Zn(o.stateElement)>0&&rt(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=Sl(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=G(e);Array.isArray(s)||rt(vr(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&rt(wr("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&rt(vr(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&rt(vr(e,"requires an array as the value when { spread: true } is set."));const d=Sl(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&rt(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=$l(t,n,o,a,d[e]);u.push(qe(a,s))}let f=0;for(let e=0;e<u.length;e++){const s=u[e];let i;i=c?r(vl(t,s,n,o),...d[e]):l?r[e]:r,void 0!==i&&(ql(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=il(e),i=Hl(t,r,n,o),a=qe(r.pathInfo,i),l=we(pe(s,a.pathInfo),a.listIndex),c=Ui();c.enqueueAbsoluteAddress(l),jl(o.stateName,o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=we(pe(s,t.pathInfo),t.listIndex);dl(e),c.enqueueAbsoluteAddress(e)}),Il(s,a.pathInfo)}}(t,0,n,o)(e);case"$resolve":return(e,s,r)=>Vl(t,0,n,o)(e,s,r);case"$trackDependency":return t=>function(t,e,n,o){return t=>{0===o.addressStackLength&&rt(`No active state reference to track dependency for path "${t}".`);const e=o.lastAddressStack?.pathInfo??rt("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 E:return da(o.stateElement);case L:return Pa(o.stateElement);case j:return _a(o.stateElement)}if(!e.startsWith(Gl)&&!e.startsWith(Kl))return}const s=il(e),r=Hl(t,s,n,o),i=qe(s.pathInfo,r);return vl(t,i,n,o)}if("symbol"==typeof e){const s=function(t){let e=Jl.get(t);return void 0===e&&(e=new Map,Jl.set(t,e)),e}(o),r=s.get(e);if(void 0!==r)return r;let i;switch(e){case ie:i=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&rt("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 ae:i=e=>vl(t,e,n,o);break;case le:i=e=>kl(t,e,n,o);break;case ce:i=(e,s)=>ql(t,e,s,n,o);break;case de:i=()=>async function(t,e,n){const o=Reflect.get(t,I);"function"==typeof o&&await o.call(n)}(t,0,n);break;case ue:i=()=>function(t,e,n){const o=Reflect.get(t,x);"function"==typeof o&&o.call(n)}(t,0,n);break;case fe:i=e=>function(t,e,n,o){const s=Reflect.get(t,P);if("function"==typeof s){const t=new Set,r={};for(const n of e){const e=n.absolutePathInfo.pathInfo;let s;if(s=n.absolutePathInfo.stateName===o.stateName?e.path:e.path+"@"+n.absolutePathInfo.stateName,t.add(s),e.wildcardCount>0){const t=Pe(n.listIndex,e.wildcardCount),o=r[s];void 0===o?r[s]=[t]:o.push(t)}}return s.call(n,Array.from(t),r)}}(t,e,n,o);break;default:return Reflect.get(t,e,n)}return s.set(e,i),i}}class Yl{_stateElement;_stateName;_addressStack=Array(i).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e,n){this._stateName=e;const o=Ti(t,this._stateName);null===o&&rt(`StateHandler: State element with name "${this._stateName}" not found.`),this._stateElement=o,this._mutability=n}get stateName(){return this._stateName}get stateElement(){return this._stateElement}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&rt("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=i&&rt(`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&&rt(`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 Xl(t,e,n,this)}set(t,e,n,o){return"readonly"===this._mutability&&rt(`State "${this._stateName}" is readonly.`),function(t,e,n,o,s){if("string"==typeof e){const r=il(e),i=Hl(t,r,o,s);return ql(t,qe(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 Ql(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)}class Zl{_webComponent;_innerStateElement;_rootMounted;_partialFirstSegments;constructor(t,e){if(this._webComponent=t,this._innerStateElement=Kn(t,e)??rt("State element not found for web component."),this._rootMounted=lo(t),this._partialFirstSegments=null,this._rootMounted){const e=ao(t);for(const t of e??[])t.isRoot||(this._partialFirstSegments??=new Set).add(t.innerAbsPathInfo.pathInfo.segments[0])}}_isPrivateKey(t,e){if(!this._rootMounted)return!1;const n=e.indexOf(s),o=-1===n?e:e.slice(0,n);return!!Object.prototype.hasOwnProperty.call(t,o)&&((null===this._partialFirstSegments||!this._partialFirstSegments.has(o))&&(!this._innerStateElement.getterPaths.has(o)&&!this._innerStateElement.setterPaths.has(o)))}_outerLoopContext(t,e){const n=e.pathInfo.wildcardCount,o=to(e.stateElement,e.pathInfo),s=te(this._webComponent);if(null!==s&&s.listIndex.length===o)return s;if(n>0){const s=function(t,e){if(0===hl)return null;const n=hl-1,o=fl[n];return ul[n]!==t||o?.pathInfo.path!==e?null:o}(this._innerStateElement,t.path),r=s?.listIndex??null;if(null!==r&&r.length===o){return qe(G(e.pathInfo.wildcardPaths[n-1]),r)}}return s}get(t,e,n){if("string"!=typeof e)return Reflect.get(t,e,n);{if("then"===e)return;if("$"===e[0])return;if(this._innerStateElement.getterPaths.has(e)&&e in t)return Reflect.get(t,e,n);if(this._isPrivateKey(t,e))return Reflect.get(t,e,n);const o=G(e),s=pe(this._innerStateElement,o),r=co(this._webComponent,s);if(null!==r){const t=this._outerLoopContext(o,r);let e;return r.stateElement.createState("readonly",n=>{n[ie](t,()=>{e=n[r.pathInfo.path]})}),e}if(e in t)return Reflect.get(t,e,n);rt(`Property "${e}" not found in inner state: no mapping rule and no local state property.`)}}set(t,e,n,o){if("string"!=typeof e)return Reflect.set(t,e,n,o);{if(this._innerStateElement.setterPaths.has(e)&&e in t)return Reflect.set(t,e,n,o);if(this._isPrivateKey(t,e))return Reflect.set(t,e,n,o);const s=G(e),r=pe(this._innerStateElement,s),i=co(this._webComponent,r);if(null!==i){const t=this._outerLoopContext(s,i);return i.stateElement.createState("writable",e=>{e[ie](t,()=>{e[i.pathInfo.path]=n})}),!0}if(e in t)return Reflect.set(t,e,n,o);rt(`Property "${e}" not found in inner state: no mapping rule and no local state property.`)}}has(t,e){if("string"==typeof e){if("$"===e[0])return!1;if((this._innerStateElement.getterPaths.has(e)||this._innerStateElement.setterPaths.has(e))&&e in t)return!0;if(this._isPrivateKey(t,e))return e in t;const n=G(e),o=pe(this._innerStateElement,n);return null!==co(this._webComponent,o)||e in t}return Reflect.has(t,e)}}class tc{_innerStateElement;constructor(t,e){this._innerStateElement=Kn(t,e)??rt("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 ec=new Set;function nc(t,e){const n=e.outerAbsPathInfo,o=te(t);if(n.pathInfo.wildcardCount>0&&null===o)return;let s;return n.stateElement.createState("readonly",t=>{t[ie](o,()=>{s=t[n.pathInfo.path]})}),s}function oc(t,e){ec.has(t)||(ec.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function sc(t,e,n){const o=ao(t);if(null===o)return;const s=function(t,e){const n=[];for(const o of Object.keys(t)){if(o.startsWith("$"))continue;if(void 0!==e&&e.has(o))continue;const s=Object.getOwnPropertyDescriptor(t,o);"function"!=typeof s.get&&"function"!=typeof s.set&&"function"!=typeof s.value&&n.push(o)}return n}(n,(r=t,i=e,sr.get(r)?.get(i)));var r,i;if(0===s.length)return;const a=t.tagName.toLowerCase();let l=null;const c=new Map;for(const t of o)t.isRoot?l=t:1===t.innerAbsPathInfo.pathInfo.segments.length&&c.set(t.innerAbsPathInfo.pathInfo.path,t);let d,u=!1;for(const n of s){const o=c.get(n);if(void 0!==o){oc(`${a}|${e}|${n}|partial`,`<${a}>.${e}.${n} is an own key of the component and is also mapped from the host ("${e}.${n}: ${o.outerAbsPathInfo.pathInfo.path}"). Today the host value wins; in v2 the own key becomes private and hides the host value. Remove the default, or drop the mapping.`);continue}if(null===l)continue;if(u||(d=nc(t,l),u=!0),"object"!=typeof d||null===d||!(n in d))continue;const s=l.outerAbsPathInfo.pathInfo.path;oc(`${a}|${e}|${n}|root`,`<${a}>.${e}.${n} is private and hides the mounted tree key "${s}.${n}" (${e}: ${s}). Remove the default to read the tree, or rename it to keep it private.`)}}const rc=t=>()=>t;function ic(t,e,n,s){!function(t,e,n){let o=Gn.get(t);o||(o=new Map,Gn.set(t,o)),o.set(e,n)}(e,n,t);const r=e.hasAttribute(o.bindAttributeName)?(ut(e)??[]).filter(t=>t.propSegments[0]===n):[];r.length>0?(!function(t,e,n){if(0===n.length)return;const o=Kn(t,e);null===o&&rt("State element not found for web component.");const s=new Map,r=new Map,i=new Set;for(const e of n){const n=io(o,e),a=n.innerAbsPathInfo.pathInfo.path;i.has(a)&&rt("Duplicate mapping rule for web component."),i.add(a);let l=so.get(t);void 0===l?so.set(t,new Set([n])):l.add(n);const c=n.innerAbsPathInfo,d=n.outerAbsPathInfo;ro.set(n,e),s.set(c,d),r.set(d,c),Xn(t,d.stateElement)}no.set(t,s),oo.set(t,r)}(e,n,r),sc(e,n,s),t.markComponentStateMapped?.(),t.setInitialState(function(t,e){const n=new Zl(t,e),o=Kn(t,e);null===o&&rt("State element not found for web component."),null===o.boundComponentStateProp&&rt("State element is not bound to any component state prop."),o.boundComponentStateProp in t||rt(`State element is not bound to a valid component state prop: ${o.boundComponentStateProp}`);const s=t[o.boundComponentStateProp];return"object"==typeof s&&null!==s||rt(`Invalid state object for component state prop: ${o.boundComponentStateProp}`),new Proxy(Ql(s),n)}(e,n))):t.setInitialState(Ql(s));const i=function(t,e){const n=new tc(t,e);return new Proxy({},n)}(e,n);if(Object.defineProperty(e,n,{get:rc(i),enumerable:!0,configurable:!0}),function(t,e){let n=Yo.get(t);n||(n=new Set,Yo.set(t,n)),n.add(e)}(e,n),_ in e){const t=e[_];"function"==typeof t?t.call(e,n).catch(t=>{rt(`Error in ${_}: ${t instanceof Error?t.message:String(t)}`)}):rt(`${_} is not a function.`)}}class ac extends li{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return Oi(t)}__state;_hasUpdatedCallback=!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(t=()=>0){return new ia(t)}(()=>Zn(this));_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_watchPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMappedComponentState=!1;_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&&rt(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){this._commandTokenNames=function(t){const e=new Set,n=t[C];if(void 0===n)return e;Array.isArray(n)||rt(`${C} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||rt(`${C} entries must be non-empty strings.`),t===E&&rt(`${C} entry "${t}" conflicts with the reserved namespace name "${E}".`),e.has(t)&&rt(`${C} entry "${t}" is duplicated.`),e.add(t);return e}(t),this._eventTokenNames=function(t){const e=new Set,n=t[M];if(void 0===n)return e;Array.isArray(n)||rt(`${M} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||rt(`${M} entries must be non-empty strings.`),e.has(t)&&rt(`${M} entry "${t}" is duplicated.`),e.add(t);return e}(t),this.__state=t,this._hasUpdatedCallback=P in t,rn(this),function(t,e,n){const o=e[T];if(void 0!==o){"object"==typeof o&&null!==o||rt(`${T} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||rt(`${T} entry "${e}" is not declared in $eventTokens.${ht(e,n)}`),"function"!=typeof s&&rt(`${T} entry "${e}" must be a function.`),sn(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=tl(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;Aa(this),wa(o=this),ga(o),ba.delete(o),Sa(this,t),this._listKeys=function(t){const e=t[D];if(void 0===e)return null;"object"==typeof e&&null!==e||rt(`${D} 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&&rt(`${D} entry path must be a non-empty string.`);const e=t.split(s);e.some(t=>0===t.length)&&rt(`${D} entry "${t}" must not contain empty path segments.`),e[e.length-1]===r&&rt(`${D} entry "${t}" must be the list path itself, not the element path (drop the trailing "${s}${r}").`),"function"!=typeof o?("string"!=typeof o&&rt(`${D} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&rt(`${D} entry "${t}" key field name must be a non-empty string.`),(o.includes(s)||o.includes(r))&&rt(`${D} entry "${t}" key field name "${o}" must be a flat property name ("${s}" / "${r}" are not allowed).`),o in Object.prototype&&rt(`${D} 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){Ra.delete(t),Oa.delete(t)}(this),function(t){Ba.delete(t)}(this),this._watchPaths=Wa(this,t),this._initialized&&null!==this._rootNode&&!e()&&(qa(this),Ea(this),this._streamsStartedGeneration=this._connectGeneration),this._resolveLoading?.()}get name(){return this._name}_loadFromSsrElement(){if(!this.hasAttribute("enable-ssr"))return null;const t=this.getAttribute("name")||"default",e=this.parentNode;if(!e)return null;const n=pi.findByName(e,t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null}async _initialize(){const t=e()?null:this._loadFromSsrElement();try{if(this.hasAttribute("state")){const t=this.getAttribute("state");this._state=function(t){const e=document.getElementById(t);if(e&&"application/json"===e.type)try{return JSON.parse(e.textContent||"{}")}catch(t){rt("Failed to parse JSON from script element:"+t)}return{}}(t)}else if(this.hasAttribute("src")){const t=this.getAttribute("src");t&&t.endsWith(".json")?this._state=await async function(t){try{const e=await fetch(t);return e.ok||rt(`Failed to fetch JSON file: ${e.statusText}`),await e.json()}catch(t){return console.error("Failed to load JSON file:",t),{}}}(t):t&&t.endsWith(".js")?this._state=await ra(t):rt(`Unsupported src file type: ${t}`)}else if(this.hasAttribute("json")){const t=this.getAttribute("json");this._state=JSON.parse(t)}else{const t=this.querySelector('script[type="module"]');if(t)this._state=await sa(t,`${this._name}`);else{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element with name="${this._name}".`)},6e4);this._state=await this._setStatePromise,clearTimeout(t)}}}catch(t){rt(`Failed to initialize state: ${t}`)}if(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,this._name=this.getAttribute("name")||"default",this.hasAttribute("name")&&!this.hasAttribute("bind-component")&&Et("attribute",this._name),Li(this.rootNode,this._name,this)}async _initializeBindWebComponent(){if(this.hasAttribute("bind-component")){const t=this.parentNode,e=t instanceof ShadowRoot?t.host:t instanceof Element?t:null,n=e?X(e):null;null!==e&&null!==n||rt(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),t instanceof ShadowRoot||this.hasAttribute("name")||rt('"bind-component" in Light DOM requires a "name" attribute to avoid namespace conflicts with the parent scope.');const s=["state","src","json"].filter(t=>this.hasAttribute(t));null!==this.querySelector('script[type="module"]')&&s.push('<script type="module">'),s.length>0&&rt(`"bind-component" cannot be combined with ${s.join(", ")}. The component's "${this.getAttribute("bind-component")}" property is the only state source.`);const r=this.getAttribute("bind-component");!function(t,e){let n=Qo.get(t);n||(n=new Set,Qo.set(t,n)),n.add(e)}(e,r);const i=Q(e);null===i&&rt(`CustomElementRegistry is unavailable for <${n}>.`),await i.whenDefined(n.toLowerCase()),e.hasAttribute(o.bindAttributeName)&&await q(e),r in e||rt(`Component does not have property "${r}" for state binding.`);let a=e[r];"object"==typeof a&&null!==a||rt(`Component property "${r}" is not an object for state binding.`);const l=function(t,e){const n=or.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(e,r);void 0!==l&&function(t,e){if(!t.hasAttribute(o.bindAttributeName))return!1;const n=ut(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(e,r)&&(e[r]=l,a=l),this._boundComponent=e,this._boundComponentStateProp=r,ic(this,this._boundComponent,this._boundComponentStateProp,a)}}_initializeLightDomComponentScope(){const t=this._boundComponent;null!==t&&this.parentNode===t&&t.hasAttribute(o.bindAttributeName)&&(si(this._rootNode,t),jr(t,null))}_reloadMappedPathsAfterReconnect(){if(!this._hasMappedComponentState||null===this._boundComponent)return;const t=function(t){const e=so.get(t);if(void 0===e)return[];const n=[];for(const t of e)t.isRoot||n.push(t.innerAbsPathInfo.pathInfo.path);return n}(this._boundComponent),e=lo(this._boundComponent)?ur(this):[];!function(t){const e=so.get(t);if(void 0===e)return;const n=new Map,o=new Map;for(const t of e)n.set(t.innerAbsPathInfo,t.outerAbsPathInfo),o.set(t.outerAbsPathInfo,t.innerAbsPathInfo);no.set(t,n),oo.set(t,o)}(this._boundComponent),this.createState("readonly",n=>{for(const e of t)n.$postUpdate(e);for(const t of e)n.$postUpdate(t)})}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{I in t&&await t[de]()})}async _initializeDCC(t,e){let n;try{if(this.hasAttribute("src")){const t=this.getAttribute("src");t.endsWith(".js")?n=await ra(t):rt(`DCC: Unsupported src type: ${t}`)}else{const e=this.querySelector('script[type="module"]');e?n=await sa(e,t.tagName.toLowerCase()):rt(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}}catch(t){rt(`DCC: Failed to load state: ${t}`)}!function(t,e,n){const s=t.tagName.toLowerCase();s.includes("-")||rt(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Q(t);null!==r&&"function"==typeof r.define||rt(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&rt(`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}=ol(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}:not([name])`,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(W))return null;this._shadow=this.attachShadow({mode:p.shadowRootMode}),this._shadow.appendChild(p.template.content.cloneNode(!0));const t=Q(this._shadow);return null!==t&&Z(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 ${A} but its template has no <${o.tagNames.state}> without a "name" attribute. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(h)??null}},m=tl(n);for(const[t,e]of Object.entries(m)){if(Za(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=Qa(t,o)}else n.get=Xa(t),n.set=Ya(t);Object.defineProperty(p.prototype,t,n)}for(const t of d)Object.defineProperty(p.prototype,t,{configurable:!0,enumerable:!0,get:Xa(t),set:Ya(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[ue]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initialized)this._dcc||Ti(this._rootNode,this._name)===this||(Li(this._rootNode,this._name,this),this._reloadMappedPathsAfterReconnect());else{const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(W))return this.hasAttribute("bind-component")&&rt(`"bind-component" cannot be used inside a [${W}] host. DCC state comes from the template, not from a component property.`),void await this._initializeDCC(t.host,t);await this._initializeBindWebComponent(),await this._initialize(),this._initialized=!0,this._initializeLightDomComponentScope(),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 Oi(this.rootNode);const t=this.getAttribute("name")||"default",e=pi.extractStateData(this),n=document.createElement(o.tagNames.ssr);n.setAttribute("name",t),n.setAttribute("version",ai),pi.buildContent(n,e),this.parentNode?.insertBefore(n,this)}catch(t){throw this._rejectConnectedCallback?.(t),t}e()||null===this._rootNode||t!==this._connectGeneration||qa(this),e()||null===this._rootNode||t!==this._connectGeneration||this._streamsStartedGeneration===t||Ea(this),this._resolveConnectedCallback?.()}disconnectedCallback(){if(null!==this._rootNode)try{this._callStateDisconnectedCallback()}finally{Li(this.rootNode,this._name,null),t=this,aa.delete(t),function(t){ca.delete(t)}(this),rn(this),wa(this),Aa(this),function(t){Ra.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}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&&rt("State rootNode is not available."),this._rootNode}get hasRootNode(){return null!==this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get boundComponent(){return this._boundComponent}get hasMappedComponentState(){return this._hasMappedComponentState}get boundPaths(){return this._pathSet}markComponentStateMapped(){this._hasMappedComponentState=!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){const e=!this._listPaths.has(t);this._listPaths.add(t),this._elementPaths.add(t+"."+r),e&&this._hasMappedComponentState&&function(t,e){const n=fo(t,G(e));null!==n&&n.stateElement!==t&&n.stateElement.setPathInfo(n.pathInfo.path,"for","internal")}(this,t)}if(!this._pathSet.has(t)){const e=G(t);if(this._pathSet.add(t),$r(this,this.__state,t,n),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=G(t.parentPath)}}}_createState(t,e,n){try{const o=function(t,e,n,o){const s=new Yl(t,n,o);return new Proxy(e,s)}(t,this._state,this._name,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)}bindProperty(t,e){Object.defineProperty(this._state,t,e),t===P&&(this._hasUpdatedCallback=!0)}setInitialState(t){this._initialized?this._state=t:this._resolveSetState?.(t)}}function lc(t=customElements){t.get(o.tagNames.ssr)||t.define(o.tagNames.ssr,pi),t.get(o.tagNames.state)||t.define(o.tagNames.state,ac)}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)),lc(o),function(){const t=globalThis;void 0===t[vi]&&(t[vi]=ki)}(),function(){const e=globalThis;void 0===e[t]&&(e[t]=ea)}(),ta()}();
2
2
  //# sourceMappingURL=auto.min.js.map