@wcstack/state 1.21.1 → 1.21.2

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/index.esm.js CHANGED
@@ -6058,7 +6058,7 @@ async function buildBindings(root) {
6058
6058
  }
6059
6059
  }
6060
6060
 
6061
- var version = "1.21.1";
6061
+ var version = "1.21.2";
6062
6062
  var pkg = {
6063
6063
  version: version};
6064
6064
 
@@ -1,2 +1,2 @@
1
- function e(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const t={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=t;function o(){return n}const s=new WeakMap;let r=0;function i(e){let t,n=s.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++r,promise:o,resolve:t},s.set(e,n),n}async function a(e){const t=i(e);await t.promise}const c=".",l="*",d=128,u="|",f={};for(let e=0;e<128;e++)f[`$${e+1}`]=e;const p=Object.freeze(f),h="$connectedCallback",m="$disconnectedCallback",g="$updatedCallback",b="$stateReadyCallback",y="$bindables",w="$commandTokens",N="$command",v="$eventTokens",S="$on",x="$streams",I="$streamStatus",A="$streamError",_="data-wc-definition",P=new Map;let $=0;function T(e){let t=P.get(e);return void 0!==t||(t=Object.freeze(new k(e)),P.set(e,t)),t}class k{id=++$;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(e){const t=t=>e===t?this:T(t),n=e.split("."),o=[],s=[],r=[],i={},a=[],c=[],d=[],u=[];let f="",p="",h=0;for(let e=0;e<n.length;e++)f+=n[e],n[e]===l&&(r.push(f),i[f]=h,a.push(t(f)),c.push(p),d.push(t(p)),u.push(e),h++),o.push(f),s.push(t(f)),p=f,f+=".";const m=r.length>0?r[r.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=e,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=r,this.wildcardPathSet=new Set(r),this.indexByWildcardPath=i,this.wildcardPathInfos=a,this.wildcardPathInfoSet=new Set(a),this.wildcardParentPaths=c,this.wildcardParentPathSet=new Set(c),this.wildcardParentPathInfos=d,this.wildcardParentPathInfoSet=new Set(d),this.wildcardPositions=u,this.lastWildcardPath=m,this.lastWildcardInfo=m?t(m):null,this.parentPath=g,this.parentPathInfo=g?t(g):null,this.wildcardCount=h}}const C=new WeakMap;function E(e){const t=C.get(e);if(void 0!==t)return t;let n=null;try{if(e.nodeType!==Node.ELEMENT_NODE)return n;const t=e,o=t.tagName.toLowerCase();if(o.includes("-"))return n=o;if(t.hasAttribute("is")){const e=t.getAttribute("is");if(e.includes("-"))return n=e}return n}finally{C.set(e,n)}}function M(e=null){const t=globalThis.customElements,n=e?.customElements??t;if("object"!=typeof n||null===n)return null;const o=n;return"function"!=typeof o.get||"function"!=typeof o.whenDefined?null:o}function O(e,t){e.upgrade?.(t)}function D(e){try{if(null===e||"object"!=typeof e&&"function"!=typeof e)return null;const t=e,n=t.addEventListener,o=t.removeEventListener,s=t.constructor?.wcBindable;if("function"!=typeof n||"function"!=typeof o)return null;if("wc-bindable"!==s?.protocol)return null;if(!Number.isInteger(s.version)||s.version<1)return null;const r=B(s.properties,R);if(null===r)return null;const i=void 0===s.inputs?new Map:B(s.inputs,L);if(null===i)return null;const a=void 0===s.commands?new Map:B(s.commands,W);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function R(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&("string"==typeof t.event&&0!==t.event.length&&(void 0===t.getter||"function"==typeof t.getter))}function L(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.attribute||"string"==typeof t.attribute)}function W(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.async||"boolean"==typeof t.async)}function B(e,t){if(!Array.isArray(e))return null;const n=new Map;for(const o of e){if(!t(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function j(e){throw new Error(`[@wcstack/state] ${e}`)}function F(e,t,n){const o="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:o,statePathInfo:T(o),stateName:n,inFilters:[],outFilters:[],bindingType:"prop"}}function z(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function q(e,t){let n=e;if(0===t.length)return n;for(let e=0;e<t.length&&(n=n?.childNodes[t[e]]??null,null!==n);e++);return n}const U=new WeakMap;function V(e){return U.get(e)||null}function H(e,t){U.set(e,t)}const G=new Set(["if","elseif","else","for"]);function J(e){j(`filter ${e} requires at least one option`)}function K(e){j(`filter ${e} requires a number as option`)}function Y(e){j(`filter ${e} requires a number value`)}function X(e){j(`filter ${e} requires a date value`)}function Q(e){return!(!e||isNaN(Number(e)))}const Z={eq:e=>{const t=e?.[0]??J("eq");return e=>"number"==typeof e?(Q(t)||K("eq"),e===Number(t)):e===t},ne:e=>{const t=e?.[0]??J("ne");return e=>"number"==typeof e?(Q(t)||K("ne"),e!==Number(t)):e!==t},not:e=>e=>("boolean"!=typeof e&&j(`filter ${"not"} requires a boolean value`),!e),lt:e=>{const t=e?.[0]??J("lt");return Q(t)||K("lt"),e=>("number"!=typeof e&&Y("lt"),e<Number(t))},le:e=>{const t=e?.[0]??J("le");return Q(t)||K("le"),e=>("number"!=typeof e&&Y("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??J("gt");return Q(t)||K("gt"),e=>("number"!=typeof e&&Y("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??J("ge");return Q(t)||K("ge"),e=>("number"!=typeof e&&Y("ge"),e>=Number(t))},inc:e=>{const t=e?.[0]??J("inc");return Q(t)||K("inc"),e=>("number"!=typeof e&&Y("inc"),e+Number(t))},dec:e=>{const t=e?.[0]??J("dec");return Q(t)||K("dec"),e=>("number"!=typeof e&&Y("dec"),e-Number(t))},mul:e=>{const t=e?.[0]??J("mul");return Q(t)||K("mul"),e=>("number"!=typeof e&&Y("mul"),e*Number(t))},div:e=>{const t=e?.[0]??J("div");return Q(t)||K("div"),e=>("number"!=typeof e&&Y("div"),e/Number(t))},mod:e=>{const t=e?.[0]??J("mod");return Q(t)||K("mod"),e=>("number"!=typeof e&&Y("mod"),e%Number(t))},fix:e=>{const t=e?.[0]??"0";return Q(t)||K("fix"),e=>("number"!=typeof e&&Y("fix"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0]??n.locale;return e=>("number"!=typeof e&&Y("locale"),e.toLocaleString(t))},uc:e=>e=>String(e).toUpperCase(),lc:e=>e=>String(e).toLowerCase(),cap:e=>e=>{const t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)},trim:e=>e=>String(e).trim(),slice:e=>{const t=[],n=e?.[0]??J("slice");Q(n)||K("slice"),t.push(Number(n));const o=e?.[1];return void 0!==o&&(Q(o)||K("slice"),t.push(Number(o))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??J("substr");Q(t)||K("substr");const n=e?.[1]??J("substr");return Q(n)||K("substr"),e=>String(e).substr(Number(t),Number(n))},pad:e=>{const t=e?.[0]??J("pad");Q(t)||K("pad");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},rep:e=>{const t=e?.[0]??J("rep");return Q(t)||K("rep"),e=>String(e).repeat(Number(t))},rev:e=>e=>String(e).split("").reverse().join(""),int:e=>e=>parseInt(String(e),10),float:e=>e=>parseFloat(String(e)),round:e=>{const t=e?.[0]??"0";return Q(t)||K("round"),e=>{"number"!=typeof e&&Y("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return Q(t)||K("floor"),e=>{"number"!=typeof e&&Y("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return Q(t)||K("ceil"),e=>{"number"!=typeof e&&Y("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return Q(t)||K("percent"),e=>("number"!=typeof e&&Y("percent"),`${(100*e).toFixed(Number(t))}%`)},date:e=>{const t=e?.[0]??n.locale;return e=>(e instanceof Date||X("date"),e.toLocaleDateString(t))},time:e=>{const t=e?.[0]??n.locale;return e=>(e instanceof Date||X("time"),e.toLocaleTimeString(t))},datetime:e=>{const t=e?.[0]??n.locale;return e=>(e instanceof Date||X("datetime"),e.toLocaleString(t))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||X("ymd");const n=e.getFullYear().toString(),o=(e.getMonth()+1).toString().padStart(2,"0"),s=e.getDate().toString().padStart(2,"0");return`${n}${t}${o}${t}${s}`}},falsy:e=>e=>!1===e||null==e||0===e||""===e||Number.isNaN(e),truthy:e=>e=>!1!==e&&null!=e&&0!==e&&""!==e&&!Number.isNaN(e),defaults:e=>{const t=e?.[0]??J("defaults");return e=>!1===e||null==e||0===e||""===e||Number.isNaN(e)?t:e},boolean:e=>e=>Boolean(e),number:e=>e=>Number(e),string:e=>e=>String(e),null:e=>e=>""===e?null:e},ee=Z,te={input:Z,output:ee},ne=(e,t)=>n=>{const o=n[e];return o||j(`filter not found: ${e}`),o(t)};const oe=new Map;function se(e,t){const n=te[t];return e.map(e=>{const o=e.indexOf("("),s=e.lastIndexOf(")");if(-1!==o&&-1===s&&j(`Invalid filter format: missing closing parenthesis in "${e}"`),-1!==s&&-1===o&&j(`Invalid filter format: missing opening parenthesis in "${e}"`),-1===o){const o=e.trim(),s=`${o}():${t}`;let r=oe.get(s);return void 0===r&&(r=ne(o,[])(n),oe.set(s,r)),{filterName:o,args:[],filterFn:r}}{const r=e.substring(o+1,s),i=e.substring(0,o).trim(),a=function(e){const t=[];let n="",o=null,s=!1;for(let r=0;r<e.length;r++){const i=e[r];o?i===o?o=null:n+=i:'"'===i||"'"===i?(o=i,s=!0):","===i?(t.push(n.trim()),n="",s=!1):n+=i}const r=n.trim();return(r||s)&&t.push(r),t}(r),c=`${i}(${a.join(",")}):${t}`;let l=oe.get(c);return void 0===l&&(l=ne(i,a)(n),oe.set(c,l)),{filterName:i,args:a,filterFn:l}}})}const re=e=>e.trim(),ie=new Map;const ae=new Map;function ce(e){const t=e.indexOf(u);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),ae.has(s)?r=ae.get(s):(o=s.split(u).map(re),r=se(o,"output"),ae.set(s,r))):n=e.trim();const[i,a="default"]=n.split("@").map(re);return{stateName:a,statePathName:i,statePathInfo:T(i),outFilters:r}}function le(e){const[...t]=e.split(";").map(re).filter(e=>e.length>0),n=t.map(e=>{const t=e.indexOf(":");-1===t&&j(`Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.`);const n=e.slice(0,t).trim(),o=e.slice(t+1).trim();if("else"===n){return{propName:"else",propSegments:["else"],propModifiers:[],statePathName:"#else",statePathInfo:T("#else"),stateName:"",inFilters:[],outFilters:[],bindingType:"else"}}if("..."===n){const t=ce(o);return t.outFilters.length>0&&j(`Invalid spread binding "${e}": filters are not allowed on spread targets.`),0===t.statePathName.length&&j(`Invalid spread binding "${e}": spread target path is required.`),{propName:"...",propSegments:["..."],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n||"radio"===n||"checkbox"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...ce(o),bindingType:n}}{const e=ce(o),t=function(e){const t=e.indexOf(u);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),ie.has(s)?r=ie.get(s):(o=s.split(u).map(re),r=se(o,"input"),ie.set(s,r))):n=e.trim();const[i,a]=n.split("#").map(re),l=i.split(c).map(re);return{propName:i,propSegments:l,propModifiers:a?a.split(",").map(re):[],inFilters:r}}(n);return"eventToken"===t.propSegments[0]||t.propSegments[0].startsWith("on")?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>G.has(e.bindingType))&&j(`Invalid bindText: "${e}". 'if', 'elseif', 'else', and 'for' bindings must be single binding.`)}return n}const de=new WeakMap,ue=new Set([n.commentTextPrefix,n.commentForPrefix,n.commentIfPrefix,n.commentElseIfPrefix,n.commentElsePrefix]),fe=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function pe(e){const t=de.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const o=e.data.trim(),s=fe.exec(o);if(null===s)return null;const r=s[1]||n.commentTextPrefix;return ue.has(r)?(de.set(e,s[2]),s[2]):null}const he=new Map;function me(e,t,n){if(null===n)he.delete(e);else{he.set(e,n);const o=n.parseBindTextResult,s=$s(t,o.stateName);null===s&&j(`State element with name "${o.stateName}" not found for fragment info.`),s.setPathInfo(o.statePathName,o.bindingType);for(const e of n.nodeInfos)for(const n of e.parseBindTextResults){const e=$s(t,n.stateName);null===e&&j(`State element with name "${n.stateName}" not found for fragment info node.`),e.setPathInfo(n.statePathName,n.bindingType)}}}function ge(e){return he.get(e)||null}function be(e){if(e.nodeType===Node.ELEMENT_NODE){return le(e.getAttribute(n.bindAttributeName)||"")}if(e.nodeType===Node.COMMENT_NODE){const t=pe(e);null===t&&j("Comment node binding text not found.");const n=ge(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o={propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...ce(t),bindingType:"text"},s=null):s=t,[{...o,uuid:s}]}return[]}function ye(e){const t=[],o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(e){if(e.nodeType===Node.ELEMENT_NODE){return e.hasAttribute(n.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==pe(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;o.nextNode();)t.push(o.currentNode);return t}const we=new WeakSet;function Ne(e,t,o){const s=function(e,t,o={}){const s=o.allowDeferred??!0;if(!t.some(e=>"spread"===e.bindingType))return t;const r=[],i=new WeakSet;for(const n of t){if("spread"!==n.bindingType){r.push(n);continue}e.nodeType!==Node.ELEMENT_NODE&&j("Spread binding requires an element node.");const t=e,o=E(t);null===o&&j(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=M();if(null===a&&j(`CustomElementRegistry is unavailable for <${o}>.`),void 0===a.get(o)){s||j(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}O(a,t);const c=D(t);null===c&&j(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const l=n.statePathName,d=n.stateName,u=new Set;for(const e of c.knownProperties.keys()){if(u.has(e))continue;u.add(e);const t=F(e,l,d);i.add(t),r.push(t)}for(const e of c.declaredInputs.keys()){if(u.has(e))continue;u.add(e);const t=F(e,l,d);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=z(r[e]);null!==t&&a.set(t,e)}const c=[];for(let t=0;t<r.length;t++){const o=z(r[t]);if(null!==o){if(a.get(o)===t)c.push(r[t]);else if(n.debug&&i.has(r[t])){const n=r[a.get(o)],s=e.nodeType===Node.ELEMENT_NODE?`<${e.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[t].propName}" of ${s} overridden by explicit binding (statePath: "${n.statePathName}").`)}}else c.push(r[t])}return c}(e,t,{allowDeferred:o.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?E(e):null;return null===n&&j("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t}}}we.add(e);const r=function(e,t){const n=[];for(const o of t)if("text"!==o.bindingType)n.push({...o,node:e,replaceNode:e});else{const t=document.createTextNode("");n.push({...o,node:e,replaceNode:t})}return n}(e,s);return H(e,r),function(e){i(e).resolve()}(e),{bindings:r,deferred:null}}function ve(e){const t=ye(e),n=[],o=[];for(const e of t){if(we.has(e))continue;const t=Ne(e,be(e),{allowDeferred:!0});null===t.deferred?n.push(...t.bindings):o.push(t.deferred)}return[t,n,o]}function Se(e){const{node:t,parseResults:n}=e;!function(e){we.delete(e)}(t);return Ne(t,n,{allowDeferred:!1}).bindings}const xe=new WeakMap;function Ie(e){let t=e;for(;t;){const e=xe.get(t);if(e)return e;t=t.parentNode}return null}function Ae(e,t){null!==t?xe.set(e,t):xe.delete(e)}const _e=new WeakMap;function Pe(e){return _e.get(e)??[]}function $e(e,t){_e.set(e,t)}const Te=Symbol("$$setLoopContextAsync"),ke=Symbol("$$setLoopContext"),Ce=Symbol("$$getByAddress"),Ee=Symbol("$$hasByAddress"),Me=Symbol("$$setByAddress"),Oe=Symbol("$$connectedCallback"),De=Symbol("$$disconnectedCallback"),Re=Symbol("$$updatedCallback"),Le=new WeakMap;function We(e,t){if(Le.has(e)){const n=Le.get(e);if(n.has(t))return n.get(t)}else Le.set(e,new WeakMap);const n=Object.freeze(new Be(e,t));return Le.get(e).set(t,n),n}class Be{pathInfo;stateName;stateElement;parentAbsolutePathInfo;constructor(e,t){this.pathInfo=t,this.stateName=e.name,this.stateElement=e,null===t.parentPathInfo?this.parentAbsolutePathInfo=null:this.parentAbsolutePathInfo=We(e,t.parentPathInfo)}}const je=new WeakMap,Fe=new WeakMap;class ze{absolutePathInfo;listIndex;_parentAbsoluteAddress;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}get parentAbsoluteAddress(){if(void 0!==this._parentAbsoluteAddress)return this._parentAbsoluteAddress;const e=this.absolutePathInfo.parentAbsolutePathInfo;if(null===e)return null;let t=null;return t=this.absolutePathInfo.pathInfo.segments[this.absolutePathInfo.pathInfo.segments.length-1]===l?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAbsoluteAddress=qe(e,t)}}function qe(e,t){if(null===t){let t=Fe.get(e);return void 0!==t||(t=new ze(e,null),Fe.set(e,t)),t}{let n=je.get(t);void 0===n&&(n=new WeakMap,je.set(t,n));let o=n.get(e);return void 0!==o||(o=new ze(e,t),n.set(e,o)),o}}const Ue=new WeakMap;function Ve(e,t){null===t?Ue.delete(e):Ue.set(e,t)}function He(e){return Ue.get(e)||null}const Ge=new Map;function Je(e,t){let n,o;if(0===e.wildcardCount||0===t.wildcardCount)return 0;if(1===e.wildcardCount&&t.wildcardCount>0&&t.wildcardPathSet.has(e.path))return 1;e.id<t.id?(n=e,o=t):(n=t,o=e);const s=`${n.path}\t${o.path}`;let r=Ge.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,Ge.set(s,r),r}const Ke=new WeakMap;function Ye(e){const t=Ie(e.node);if(null===t)return null;let n=Ke.get(t);if(void 0===n)n=new WeakMap,Ke.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=Je(t.pathInfo,e.statePathInfo);return n>0&&(o=t.listIndex.at(n-1)),o}finally{n.set(e,o)}}const Xe=new WeakMap;function Qe(e){let t=null;if(t=Xe.get(e)||null,null!==t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=He(n);null===t?j(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}const o=Ye(e),s=$s(n,e.stateName);null===s&&j(`State element with name "${e.stateName}" not found for binding.`);return t=qe(We(s,e.statePathInfo),o),Xe.set(e,t),t}function Ze(e){Xe.delete(e)}let et=null;const tt=new WeakMap;function nt(e){return tt.get(e)}function ot(e,t){const n=function(e){let t=null;return t=tt.get(e)||null,null===t&&(t=new Set,tt.set(e,t)),t}(e);n.add(t),null!==et&&et({type:"state:binding-added",absoluteAddress:e,binding:t})}function st(e,t){const n=tt.get(e);void 0!==n&&(n.delete(t),null!==et&&et({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const rt=new WeakMap,it=new WeakMap;class at{pathInfo;listIndex;_parentAddress;constructor(e,t){this.pathInfo=e,this.listIndex=t}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const e=this.pathInfo.parentPathInfo;if(null===e)return null;let t=null;return t=this.pathInfo.segments[this.pathInfo.segments.length-1]===l?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=ct(e,t)}}function ct(e,t){if(null===t){let t=it.get(e);return void 0!==t||(t=new at(e,null),it.set(e,t)),t}{let n=rt.get(t);void 0===n&&(n=new WeakMap,rt.set(t,n));let o=n.get(e);return void 0!==o||(o=new at(e,t),n.set(e,o)),o}}const lt=new WeakMap;function dt(e){let t=null;if(t=lt.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=Ye(e);null===n&&j(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=ct(e.statePathInfo,n)}else t=ct(e.statePathInfo,null);return lt.set(e,t),t}function ut(e){lt.delete(e)}function ft(){const e=new Map,t=new Map;return{add(n,o){let s=e.get(n);return void 0===s&&(s=new WeakSet,e.set(n,s)),!s.has(o)&&(s.add(o),t.set(n,(t.get(n)??0)+1),!0)},remove(n,o){const s=e.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(t.get(n)??1)-1;return r<=0?(e.delete(n),t.delete(n),!0):(t.set(n,r),!1)},has:(t,n)=>e.get(t)?.has(n)??!1,countOf:e=>t.get(e)??0,get keyCount(){return t.size},clear(){e.clear(),t.clear()}}}const pt=new Map,ht=ft();function mt(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.stateName}::${e.statePathName}::${t}::${n}`}function gt(e){let t="input";for(const n of e.propModifiers)n.startsWith("on")&&(t=n.slice(2));return t}function bt(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf("ro")){const s=gt(e),r=mt(e,s);let i=pt.get(r);return void 0===i&&(t=e.stateName,n=e.statePathName,o=e.inFilters,i=e=>{const s=e.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 e of o)i=e.filterFn(i);const a=$s(s.getRootNode(),t);null===a&&j(`State element with name "${t}" not found for two-way binding.`);const c=Ie(s);a.createState("writable",e=>{e[ke](c,()=>{let t=e[n];if(Array.isArray(t))if(r)-1===t.indexOf(i)&&(e[n]=t.concat(i));else{const o=t.indexOf(i);-1!==o&&(e[n]=t.toSpliced(o,1))}else e[n]=r?[i]:[]})})},pt.set(r,i)),e.node.addEventListener(s,i),ht.add(r,e),!0}var t,n,o;return!1}class yt{_name;_subscribers=new Set;constructor(e){this._name=e}get name(){return this._name}get size(){return this._subscribers.size}subscribe(e){return this._subscribers.add(e),()=>{this._subscribers.delete(e)}}unsubscribe(e){return this._subscribers.delete(e)}emit(...e){const t=[];for(const n of this._subscribers)t.push(n(...e));return t}}class wt extends yt{_ownerStateName;constructor(e,t){super(e),this._ownerStateName=t??null}emit(...e){return null!==et&&et({type:"state:token-emit",kind:"event",stateName:this._ownerStateName,tokenName:this.name,args:e,subscriberCount:this.size}),super.emit(...e)}}const Nt=new WeakMap;function vt(e,t){let n=Nt.get(e);void 0===n&&(n=new Map,Nt.set(e,n));let o=n.get(t);return void 0===o&&(o=new wt(t,e.name),n.set(t,o)),o}function St(e){Nt.delete(e)}const xt=new WeakMap;function It(e){if("eventToken"!==e.propSegments[0])return!1;const t=e.node,n=E(t),o=M();if(null!==n&&void 0===o?.get(n))return null===o&&j(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(xt.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||j('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===E(e)?null:D(e)}(t);null===r&&j(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&j(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.`);const a=i.event,c=e.statePathName,l=e.stateName,d=e.propModifiers,u=e=>{d.includes("prevent")&&e.preventDefault(),d.includes("stop")&&e.stopPropagation();const n=$s(t.getRootNode(),l);null===n&&j(`State element with name "${l}" not found for eventToken handler.`),n.eventTokenNames.has(c)||j(`eventToken "${c}" is not declared in $eventTokens of state "${l}".`);const o=Ie(t);n.createStateAsync("writable",async t=>{t[ke](o,()=>{const s=o?.listIndex.indexes??[];return vt(n,c).emit(t,e,...s)})})};return t.addEventListener(a,u),xt.set(e,{eventName:a,handler:u}),!0}class At extends yt{_ownerStateName;constructor(e,t){super(e),this._ownerStateName=t??null}emit(...e){return null!==et&&et({type:"state:token-emit",kind:"command",stateName:this._ownerStateName,tokenName:this.name,args:e,subscriberCount:this.size}),super.emit(...e)}}function _t(e){return e instanceof At}const Pt=new Map,$t=ft();function Tt(e){const t=e.propModifiers.filter(e=>"prevent"===e||"stop"===e).sort().join(",");return`${e.stateName}::${e.statePathName}::${t}`}const kt=(e,t,n,o)=>s=>{n.includes("prevent")&&s.preventDefault(),n.includes("stop")&&s.stopPropagation();const r=s.target,i=$s(r.getRootNode(),e);null===i&&j(`State element with name "${e}" not found for event handler.`);const a=Ie(r),c=t.startsWith(N+".");i.createStateAsync("writable",async n=>{n[ke](a,()=>{const r=a?.listIndex.indexes??[];if(c){const e=n[Ce](ct(o,null));return _t(e)||j(`Event binding "${t}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),e.emit(s,...r)}const i=n[t];return"function"!=typeof i&&j(`Handler "${t}" is not a function on state "${e}".`),Reflect.apply(i,n,[s,...r])})})};const Ct=new Map,Et=ft();function Mt(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.stateName}::${e.statePathName}::${t}::${n}`}function Ot(e){let t="input";for(const n of e.propModifiers)n.startsWith("on")&&(t=n.slice(2));return t}function Dt(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf("ro")){const s=Ot(e),r=Mt(e,s);let i=Ct.get(r);return void 0===i&&(t=e.stateName,n=e.statePathName,o=e.inFilters,i=e=>{const s=e.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 e of o)r=e.filterFn(r);const i=$s(s.getRootNode(),t);null===i&&j(`State element with name "${t}" not found for two-way binding.`);const a=Ie(s);i.createState("writable",e=>{e[ke](a,()=>{e[n]=r})})},Ct.set(r,i)),e.node.addEventListener(s,i),Et.add(r,e),!0}var t,n,o;return!1}const Rt=new Set(["radio","checkbox"]),Lt=new Set(["value","valueAsNumber","valueAsDate"]);function Wt(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return!1;const n=e,o=n.tagName.toLowerCase();if("input"===o){const e=(n.getAttribute("type")||"text").toLowerCase();if("button"===e)return!1;if(Rt.has(e)&&"checked"===t)return!0;if(Lt.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=E(n);if(null!==s){const e=M()?.get(s);void 0===e&&j(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=D(n);if(o?.knownProperties.has(t))return!0}return!1}let Bt=1,jt=1,Ft=1;const zt=new WeakMap;function qt(e,t,n,o){let s=zt.get(e);void 0===s&&(s=new Map,zt.set(e,s));const r=function(e,t,n){return`${t}::${n}::${e}`}(t,n,o);let i=s.get(r);return void 0===i&&(i=Bt++,s.set(r,i)),i}function Ut(e,t){return"to-element"===t?2*e:2*e+1}const Vt=new Set;function Ht(e){return{transactionId:jt++,originBindingId:e,visitedEdges:Vt,hop:0}}function Gt(e,t){const n=new Set(e.visitedEdges);return n.add(t),{transactionId:e.transactionId,originBindingId:e.originBindingId,visitedEdges:n,hop:e.hop+1}}let Jt=null;function Kt(){return Jt}function Yt(e,t){const n=Jt;Jt=e;try{return t()}finally{Jt=n}}const Xt=[];const Qt=new Map,Zt=ft(),en=new WeakMap,tn=e=>e.detail;function nn(e,t,n){const o=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.stateName}::${e.propName}::${e.statePathName}::${t}::${o}::${n?"g":"n"}`}function on(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=E(e.node);if(null!==n){const o=M()?.get(n);void 0===o&&j(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=D(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith("on")&&(t=n.slice(2));return t}function sn(e){if(null!==E(e.node)){const t=D(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??tn}return null}const rn=(e,t,o,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let c;if(null!==r)c=r(i);else{if(!(t in a))return void console.warn(`[@wcstack/state] Property "${t}" does not exist on target element.`);c=a[t]}let l=c;for(const e of s)l=e.filterFn(l);const d=en.get(a)?.get(t);if(void 0!==d)for(const e of d)e(l);let u=null;if(n.enablePropagationContext){const s=qt(a,t,e,o),r=function(e,t){for(let n=Xt.length-1;n>=0;n--){const o=Xt[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,t);if(null!==r&&Object.is(r.writtenValue,c))return n.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:t,statePathName:o,transactionId:r.transactionId,coveredBySameValueGuard:n.sameValueGuard&&(null===l||"object"!=typeof l)}),void(null!==et&&et({type:"propagation:suppressed",reason:"confirmation",transactionId:r.transactionId,edgeId:Ut(s,"to-state"),node:a,member:t}));const i=Ut(s,"to-state"),d=Kt();if(null!==d&&d.visitedEdges.has(i))return void(null!==et&&et({type:"propagation:suppressed",reason:"visited-edge",transactionId:d.transactionId,edgeId:i,node:a,member:t}));u=Gt(d??Ht(s),i)}const f=$s(a.getRootNode(),e);null===f&&j(`State element with name "${e}" not found for two-way binding.`);const p=Ie(a),h=()=>{f.createState("writable",e=>{e[ke](p,()=>{e[o]=l})})};null!==u?Yt(u,h):h()};class an{registry;entries=new Map;constructor(e){this.registry=e}wait(e,t,n=()=>{}){const o=e.toLowerCase();let s=this.entries.get(o);void 0===s&&(s={waiters:new Set},this.entries.set(o,s),this.registry.whenDefined(o).then(()=>this.settle(o,null),e=>this.settle(o,e)));const r={active:!0,resolve:t,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(e){return this.entries.get(e.toLowerCase())?.waiters.size??0}settle(e,t){const n=this.entries.get(e);if(void 0===n)return;this.entries.delete(e);const o=Array.from(n.waiters);n.waiters.clear();for(const e of o)e.active&&(e.active=!1,null===t?e.resolve():e.reject(t))}}const cn=new WeakMap;function ln(e){let t=cn.get(e);return void 0===t&&(t=new an(e),cn.set(e,t)),t}function dn(e,t){let n=null;for(const o of e.propModifiers){const e=o.indexOf("=");if(e<0)continue;const s=o.slice(0,e).trim(),r=o.slice(e+1).trim();"init"!==s&&"sync"!==s&&j(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&j(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function un(e){return e.propModifiers.some(e=>e.includes("="))}function fn(e){if(!n.enableDirectionalInitialSync)return un(e)&&j("init=/sync= modifiers require enableDirectionalInitialSync."),{authority:"state",syncOn:"call",observable:!1};const t=null===(o=dn(e,"init"))?null:"state"===o||"element"===o||"auto"===o||"none"===o?o:j(`Invalid init modifier value "${o}".`);var o;const s=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":j(`Invalid sync modifier value "${e}".`)}(dn(e,"sync"));if("event"===e.bindingType)return null!==t&&"none"!==t&&j("Event bindings only allow init=none."),{authority:"none",syncOn:s,observable:!1};if("command"===e.propSegments[0])return{authority:"state",syncOn:s,observable:!1};if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&j(`Binding type "${e.bindingType}" does not support init=${t}.`),{authority:t??"state",syncOn:s,observable:!1};const r=D(e.node);if(null===r)return{authority:t??"state",syncOn:s,observable:!1};const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||j(`Property "${e.propName}" is not declared by wcBindable.`);const c=t??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(c)||j(`init=${c} is incompatible with wcBindable member "${e.propName}".`),"connect"!==s||i||j(`sync=connect requires observable property "${e.propName}".`),{authority:c,syncOn:s,observable:i}}function pn(e,t){return"auto"!==t?t:function(e){const t=$s(e.replaceNode.getRootNode(),e.stateName);null===t&&j(`State element with name "${e.stateName}" not found for binding.`);const n=dt(e);let o=!1;return t.createState("readonly",e=>{o=e[Ee](n)}),o}(e)?"state":"element"}let hn=0,mn=0;const gn=new WeakMap,bn=new WeakMap;function yn(e,t){t(e);for(const n of Array.from(e.childNodes))yn(n,t)}class wn{root;sessionRefs=new Set;knownSessions=new WeakSet;observer;constructor(e){this.root=e;const t=globalThis.MutationObserver;this.observer="function"==typeof t?new t(e=>this.handleMutations(e)):null,this.observer?.observe(e,{childList:!0,subtree:!0})}add(e){this.knownSessions.has(e)||(this.knownSessions.add(e),this.sessionRefs.add(new WeakRef(e)))}handleMutations(e){const t=[],n=[];for(const o of e)t.push(...Array.from(o.removedNodes)),n.push(...Array.from(o.addedNodes));for(const e of Array.from(this.sessionRefs)){const o=e.deref();void 0!==o?o.handleMutations(this.root,t,n):this.sessionRefs.delete(e)}}}const Nn=new WeakMap;class vn{records=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(e=null){null!==e&&this.observe(e)}initialize(e,t={}){const n=t.registerAddress??!0,o={registerAddress:n,registerPathInfo:t.registerPathInfo??n,applyOnReconnect:t.applyOnReconnect??!0},s=[];for(const t of e){const e=this.remember(t,o),n=gn.get(e);void 0===n||"disposed"===n.phase||"failed"===n.phase?(this.start(e,o),s.push(e)):(this.observe(n.anchor),o.registerAddress&&null===n.address&&(n.options.registerAddress=!0,this.registerAddress(n)),"active"===n.phase&&this.settleInitialRecord(n),this.settleConnectedSnapshot(n))}return s.filter(e=>this.shouldApplyState(e))}shouldApplyState(e){if(!n.enableDirectionalInitialSync)return un(e)&&fn(e),!0;const t=gn.get(e);return void 0===t||t.session!==this||(!t.options.registerAddress||"waiting-definition"===t.phase||("active"===t.phase&&this.settleInitialRecord(t),"state"===t.resolvedAuthority))}getRecord(e){const t=gn.get(e);return t?.session===this?t:null}addTeardown(e,t){const n=gn.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(n.teardowns.add(t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=M();null===s&&j(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e);const r={node:e,active:!0,cancel:null};let i=this.deferredByNode.get(e);void 0===i&&(i=new Set,this.deferredByNode.set(e,i)),i.add(r),this.deferred.add(r);const a=()=>!!r.active&&(r.active=!1,i?.delete(r),this.deferred.delete(r),!0);return r.cancel=ln(s).wait(t,()=>{if(a())try{O(s,e),n()}catch(e){o(e)}},e=>{a()&&o(e)}),()=>{a()&&r.cancel?.()}}disposeBinding(e){const t=gn.get(e);void 0!==t&&t.session===this&&this.disposeRecord(t)}dispose(){for(const e of Array.from(this.records))this.disposeRecord(e);for(const e of Array.from(this.deferred))e.active=!1,e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}observe(e){const t=function(e){const t=e.getRootNode();return function(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}(t)?t:null}(e);null!==t&&function(e){let t=Nn.get(e);return void 0===t&&(t=new wn(e),Nn.set(e,t)),t}(t).add(this)}handleMutations(e,t,n){for(const n of t)yn(n,t=>{if(e.contains(t))return;const n=this.knownBindingsByNode.get(t);if(void 0!==n)for(const e of n.values())this.disposeBinding(e);const o=this.deferredByNode.get(t);if(void 0!==o)for(const e of Array.from(o))e.active=!1,e.cancel?.(),o.delete(e),this.deferred.delete(e)});const o=[];for(const t of n)yn(t,t=>{if(!e.contains(t))return;const n=this.knownBindingsByNode.get(t);if(void 0!==n)for(const e of n.values()){const t=gn.get(e);if("active"===t?.phase){this.settleConnectedSnapshot(t);continue}if("disposed"!==t?.phase)continue;const n=this.optionsByBinding.get(e);if(void 0!==n)try{this.start(e,n),n.applyOnReconnect&&this.shouldApplyState(e)&&o.push(e)}catch{}}});o.length>0&&zo(o)}remember(e,t){const n=e.replaceNode;let o=this.knownBindingsByNode.get(n);void 0===o&&(o=new Map,this.knownBindingsByNode.set(n,o));const s=function(e){const t=e.inFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|"),n=e.outFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.bindingType,e.propName,e.propModifiers.join(","),e.stateName,e.statePathName,t,n,e.uuid??""].join("\0")}(e),r=o.get(s);if(void 0!==r){const e=this.optionsByBinding.get(r);return void 0!==e&&(e.registerAddress||=t.registerAddress,e.registerPathInfo||=t.registerPathInfo,e.applyOnReconnect||=t.applyOnReconnect),r}return o.set(s,e),this.optionsByBinding.set(e,{...t}),e}start(e,t){!function(e){const t=e.node,n=e.replaceNode;t!==n&&null!==t.parentNode&&t.parentNode.replaceChild(n,t)}(e);const n=this.optionsByBinding.get(e)??{...t},o={id:++hn,info:e,generation:++mn,phase:"discovered",teardowns:new Set,session:this,anchor:e.replaceNode,options:n,address:null,pendingDefinitions:0,initialPolicy:null,resolvedAuthority:null,initialSettled:!1,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0};gn.set(e,o),this.records.add(o),this.observe(o.anchor);try{o.phase="attaching",this.attachListeners(o),o.options.registerAddress&&this.registerAddress(o),0===o.pendingDefinitions&&(o.phase="active")}catch(e){throw o.phase="failed",this.runTeardowns(o),this.records.delete(o),e}}attachListeners(e){const t=e.info;!function(e){if(!e.propName.startsWith("on"))return!1;const t=Tt(e);let n=Pt.get(t);void 0===n&&(n=kt(e.stateName,e.statePathName,e.propModifiers,e.statePathInfo),Pt.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),$t.add(t,e),!0}(t)?"eventToken"!==t.propSegments[0]?(Dt(t)&&e.teardowns.add(()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf("ro")){const t=Ot(e),n=Mt(e,t),o=Ct.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Et.countOf(n)&&(Et.remove(n,e)&&Ct.delete(n),!0))}return!1}(t)),bt(t)&&e.teardowns.add(()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf("ro")){const t=gt(e),n=mt(e,t),o=pt.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==ht.countOf(n)&&(ht.remove(n,e)&&pt.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(n.enableDirectionalInitialSync&&Wt(t.node,t.propName)&&-1===t.propModifiers.indexOf("ro")){const n=function(e,t,n){let o=en.get(e);void 0===o&&(o=new Map,en.set(e,o));let s=o.get(t);return void 0===s&&(s=new Set,o.set(t,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(t),0===o?.size&&en.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});e.teardowns.add(n)}!function(e){const t=E(e.node);if(null!==t){const e=M(),n=e?.get(t);if(void 0===n)return void(null===e&&j(`CustomElementRegistry is unavailable for <${t}>.`))}if(Wt(e.node,e.propName)&&-1===e.propModifiers.indexOf("ro")){const t=on(e),n=sn(e),o=nn(e,t,null!==n);let s=Qt.get(o);void 0===s&&(s=rn(e.stateName,e.propName,e.statePathName,e.inFilters,n),Qt.set(o,s)),e.node.addEventListener(t,s),Zt.add(o,e)}}(t),e.teardowns.add(()=>function(e){const t=E(e.node);if(null!==t){const e=M(),n=e?.get(t);if(void 0===n)return}if(Wt(e.node,e.propName)&&-1===e.propModifiers.indexOf("ro")){const t=on(e),n=nn(e,t,null!==sn(e)),o=Qt.get(n);if(void 0===o)return;e.node.removeEventListener(t,o),Zt.remove(n,e)&&Qt.delete(n)}}(t))})):this.attachAfterDefinition(e,()=>{It(t)&&e.teardowns.add(()=>function(e){if("eventToken"!==e.propSegments[0])return!1;const t=xt.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),xt.delete(e),!0)}(t))}):e.teardowns.add(()=>function(e){if(!e.propName.startsWith("on"))return!1;const t=Tt(e),n=Pt.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==$t.countOf(t)&&($t.remove(t,e)&&Pt.delete(t),!0)}(t))}attachAfterDefinition(e,t){const n=E(e.info.node);if(null===n)return void t();const o=M();if(null===o&&j(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void t();e.phase="waiting-definition",e.pendingDefinitions+=1;const s=e.generation,r=ln(o).wait(n,()=>{if(this.isAlive(e,s))try{O(o,e.info.node),t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e))}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))});e.teardowns.add(r)}settleInitialRecord(e){if(n.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=fn(e.info),n=pn(e.info,t.authority);if(e.initialPolicy=t,e.resolvedAuthority=n,e.initialSettled=!0,e.phase="active",!t.observable)return;if("connect"===t.syncOn&&e.info.node instanceof HTMLElement&&!e.info.node.isConnected)return void(e.observationPending=!0);this.readProducerSnapshot(e,"call"===t.syncOn)}catch(t){throw e.phase="failed",this.runTeardowns(e),this.records.delete(e),t}}}readProducerSnapshot(e,t){if(!this.isAlive(e,e.generation))return;const n=e.info.node,o=e.info.propName;if(!(o in n))return;const s=e.eventSequence,r=n[o];e.observationPending=!1,t&&e.eventSequence!==s||(e.hasProducerValue=!0,e.producerValue=r,"element"===e.resolvedAuthority&&function(e,t){let n=t;for(const t of e.inFilters)n=t.filterFn(n);const o=$s(e.node.getRootNode(),e.stateName);null===o&&j(`State element with name "${e.stateName}" not found for initial binding sync.`);const s=Ie(e.node);o.createState("writable",t=>{t[ke](s,()=>{t[e.statePathName]=n})})}(e.info,r))}settleConnectedSnapshot(e){if(n.enableDirectionalInitialSync&&e.observationPending&&e.info.node instanceof HTMLElement&&e.info.node.isConnected)try{this.readProducerSnapshot(e,!1)}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}}registerAddress(e){if(null!==e.address)return;const t=e.info,n=Qe(t);if(ot(n,t),e.address=n,e.teardowns.add(()=>{null!==e.address&&(st(e.address,t),e.address=null,ut(t),Ze(t))}),!e.options.registerPathInfo)return;const o=$s(t.replaceNode.getRootNode(),t.stateName);null===o&&j(`State element with name "${t.stateName}" not found for binding.`),"event"!==t.bindingType&&o.setPathInfo(t.statePathName,t.bindingType)}isAlive(e,t){return e.generation===t&&gn.get(e.info)===e&&"disposed"!==e.phase&&"failed"!==e.phase}disposeRecord(e){"disposed"!==e.phase&&(e.phase="disposed",this.runTeardowns(e),this.records.delete(e))}runTeardowns(e){const t=Array.from(e.teardowns).reverse();e.teardowns.clear();for(const e of t)try{e()}catch{}}}function Sn(e){let t=bn.get(e);return void 0===t&&(t=new vn(e),bn.set(e,t)),t}function xn(e){return gn.get(e)?.session??null}const In=new WeakMap;function An(e,t){const n=In.get(e);return!!n&&!0===n.get(t)}function _n(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const Pn=Object.freeze([]);const $n=new WeakMap;const Tn=new WeakMap;function kn(e){return Tn.get(e)??[]}function Cn(e,t){Tn.set(e,t)}Set.prototype.difference||(Set.prototype.difference=function(e){const t=new Set(this);for(const n of e)t.delete(n);return t}),Set.prototype.intersection||(Set.prototype.intersection=function(e){const t=new Set;for(const n of e)this.has(n)&&t.add(n);return t});let En=0;function Mn(){return`u${(En++).toString(36)}`}let On=0;class Dn{uuid=Mn();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;constructor(e,t){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._index=t,this._version=On}get index(){return this._index}set index(e){this._index=e,this._version=++On,this.indexes[this.position]=e}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=On),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(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function Rn(e,t){return new Dn(e,t)}const Ln=new WeakMap;function Wn(e){return Ln.get(e)||null}function Bn(e,t){null!==t?Ln.set(e,t):Ln.delete(e)}const jn=new WeakMap,Fn=Object.freeze([]),zn=new Set;function qn(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:Fn,s=Array.isArray(n)&&n.length>0?n:Fn,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Fn,o=Array.isArray(t)&&t.length>0?t:Fn;let s=jn.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Wn(o)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:zn,deleteIndexSet:new Set(i),addIndexSet:zn};let t=Wn(s);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=Rn(e,n);t.push(o)}}return a={oldIndexes:i,newIndexes:t,changeIndexSet:zn,deleteIndexSet:zn,addIndexSet:new Set(t)}}if(function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}(o,s))return a={oldIndexes:i,newIndexes:i,changeIndexSet:zn,deleteIndexSet:zn,addIndexSet:zn};if(null!==t)return function(e,t){const n=new Set(t),o=new Set(e),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let t=0;t<e.length;t++)a.set(e[t],t);for(let e=0;e<t.length;e++){const n=t[e];r.has(n)||a.get(n)!==e&&s.add(n)}return{oldIndexes:e,newIndexes:t,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,t);t=[];const n=new Map;for(let e=0;e<o.length;e++){const t=o[e];let s=n.get(t);s||(s=[],n.set(t,s)),s.push(e)}const r=new Set,c=new Set;for(let o=0;o<s.length;o++){const a=s[o],l=n.get(a),d=l&&l.length>0?l.shift():void 0;if(void 0===d){const n=Rn(e,o);t.push(n),c.add(n)}else{const e=i[d];d!==o&&r.add(e),t.push(e)}}return a={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:c}}finally{void 0!==a&&(!function(e,t,n){let o=jn.get(e);o||(o=new WeakMap,jn.set(e,o)),o.set(t,n)}(o,s,a),Bn(s,a.newIndexes))}}(e,t,n);return function(e){for(let t=0;t<e.length;t++)e[t].index!==t&&(e[t].index=t)}(o.newIndexes),o}function Un(e){if(0===e.changeIndexSet.size||e.addIndexSet.size===e.newIndexes.length)return null;const t=new Map;for(let n=0;n<e.oldIndexes.length;n++)t.set(e.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of e.newIndexes){if(e.addIndexSet.has(i))continue;const a=t.get(i);if(void 0===a)return null;a<s&&(r=!1),s=a,n.push(i),o.push(a)}if(r)return null;const i=function(e){const t=e.length,n=[],o=new Array(t).fill(-1);for(let s=0;s<t;s++){const t=e[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;e[n[o]]<t?r=o+1:i=o}r>0&&(o[s]=n[r-1]),n[r]=s}const s=[];let r=n.length>0?n[n.length-1]:-1;for(;r>=0;)s.push(r),r=o[r];return s.reverse(),s}(o),a=new Set;for(const e of i)a.add(n[e]);return a}const Vn=new WeakMap;function Hn(e){return Vn.get(e)??[]}function Gn(e,t){Vn.set(e,t)}const Jn=new WeakMap;function Kn(e){return Jn.get(e)??null}function Yn(e,t){Jn.set(e,t)}const Xn=new WeakMap;function Qn(e){return Xn.get(e)??[]}function Zn(e,t){Xn.set(e,t)}function eo(e,t){const n=Qn(e);for(const e of n)Ae(e,t)}function to(e,t,n){eo(e,t);const o=Hn(e),s=Kn(e);null!==s&&s.initialize(o,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});for(const e of o){if(null===s){ot(Qe(e),e)}(null===s||s.shouldApplyState(e))&&Fo(e,n)}}function no(e){if(!e.mounted)return;const t=Hn(e),n=Kn(e);for(const e of t)if(null!==n)n.disposeBinding(e);else{st(Qe(e),e)}!function(e){const t=Qn(e);for(const e of t)Ae(e,null)}(e)}const oo=new WeakMap,so=Object.freeze(new Set);function ro(e,t){const n=oo.get(e);n?n.add(t):oo.set(e,new Set([t]))}function io(e){const t=oo.get(e);return void 0!==t?t:so}const ao=new Set(["if","elseif","else","for"]);class co{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;constructor(e){this._content=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(e){for(const t of this._childNodeArray)e.appendChild(t);this._mounted=!0}mountAfter(e){const t=e.parentNode,n=e.nextSibling;if(t)for(const e of this._childNodeArray)t.insertBefore(e,n);this._mounted=!0}unmount(){Kn(this)?.dispose();for(const e of this._childNodeArray)null!==e.parentNode&&e.parentNode.removeChild(e);const e=Hn(this);for(const t of e){if(ao.has(t.bindingType)){const e=io(t.node);for(const t of e)t.unmount()}ut(t),Ze(t)}this._mounted=!1}}function lo(e){const t=document.createDocumentFragment(),n=new co(t);return n._childNodeArray=e,n._firstNode=e.length>0?e[0]:null,n._lastNode=e.length>0?e[e.length-1]:null,n._mounted=!0,n}function uo(e){void 0!==e.uuid&&null!==e.uuid||j("BindingInfo.uuid is null.");const t=ge(e.uuid);t||j(`Fragment with UUID "${e.uuid}" not found.`);const n=document.importNode(t.fragment,!0),o=function(e,t){const[n,o]=function(e,t){const n=[],o=[];for(const s of t){const t=q(e,s.nodePath);if(null===t&&j(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),we.has(t))continue;const r=Ne(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new vn,r=s.initialize(o,{registerAddress:!1,applyOnReconnect:!1});return{nodes:n,bindingInfos:r,bindingSession:s}}(n,t.nodeInfos),s=new co(n);Yn(s,o.bindingSession),Gn(s,o.bindingInfos);const r=[];for(const e of o.bindingInfos)e.statePathName in p&&r.push(e);return Cn(s,r),Zn(s,o.nodes),ro(e.node,s),s}const fo=new WeakMap,po=new WeakMap,ho=new WeakMap,mo=new WeakMap;function go(e,t,n){So(e,t,n)}function bo(e,t){fo.set(e,t)}function yo(e){return ho.get(e.node)||[]}function wo(e,t){let n=ho.get(e.node);void 0===n&&(n=[],ho.set(e.node,n)),n.length<1e3?n.push(t):function(e,t){const n=oo.get(e);n&&(n.delete(t),0===n.size&&oo.delete(e))}(e.node,t)}function No(e,t){if(null===t)return!1;if(e.nextSibling===t)return!0;const n=e.compareDocumentPosition(t);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}function vo(e,t){let n=po.get(e);if(void 0===n)return null;const o=n.get(t);return void 0===o?null:o}function So(e,t,n){let o=po.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,po.set(e,o)}null===n?o.delete(t):o.set(t,n)}const xo=new WeakMap;function Io(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function Ao(t,o,s){const r=t.node.isConnected,i=Boolean(s);let a;const c=io(t.node);a=0===c.size?uo(t):c.values().next().value;const l=e(),d=t.uuid??"",u=t.bindingType;try{if(i||(n.debug&&console.log(`unmount if content : ${Io(t)}`),no(a),a.unmount()),i){if(n.debug&&console.log(`mount if content : ${Io(t)}`),l){const e=document.createComment(`@@wcs-${u}-start:${d}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),a.mountAfter(e);const n=document.createComment(`@@wcs-${u}-end:${d}:${t.statePathName}`),o=a.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}else a.mountAfter(t.node);to(a,Ie(t.node),o)}}finally{xo.set(t.node,r)}}const _o=new WeakMap;function Po(e){return _o.get(e)??[]}const $o=new Set;const To={value(e,t){"TEXTAREA"===e.tagName?e.textContent=String(t??""):e.setAttribute("value",String(t??""))},checked(e,t){t?e.setAttribute("checked",""):e.removeAttribute("checked")},selected(e,t){t?e.setAttribute("selected",""):e.removeAttribute("selected")},disabled(e,t){t?e.setAttribute("disabled",""):e.removeAttribute("disabled")},selectedIndex(e,t){const n=e.querySelectorAll("option"),o=Number(t);for(let e=0;e<n.length;e++)e===o?n[e].setAttribute("selected",""):n[e].removeAttribute("selected")}};function ko(t,o,s){if(void 0===s)return void(n.debug&&console.debug("Skipped property write: state value is undefined.",{element:t.node,propSegments:t.propSegments,statePathName:t.statePathName}));const r=t.node,i=t.propSegments;if(1===i.length){const c=i[0];if(r[c]!==s){const e=()=>{let e=!1;try{r[c]=s,e=!0}catch(e){n.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:e})}if(e){const e=function(e,t){const n=E(e);if(null===n)return null;const o=M()?.get(n);if(void 0===o)return null;const s=D(e)?.declaredInputs.get(t);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==e)try{!function(e,t,n){if(null==n)return void e.removeAttribute(t);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);e.setAttribute(t,o)}(r,e,s)}catch(t){n.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:s,error:t})}}};if(n.enablePropagationContext&&Wt(r,c)){const n=qt(r,c,t.stateName,t.statePathName),i=Ut(n,"to-element"),a=o?.propagationContextByBinding?.get(t)??Kt()??Ht(n);if(a.visitedEdges.has(i))null!==et&&et({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:i,node:r,member:c});else{const t=Gt(a,i);Yt(t,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:Ft++,writtenValue:n};Xt.push({receipt:i,node:e});try{return r()}finally{Xt.pop()}}(r,c,s,n,t.transactionId,e))}}else e()}if(e()){const e=To[c];e?e(r,s):(!function(e,t,n){let o=_o.get(e);o||(o=[],_o.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,c,s),a=r,$o.add(a))}return}var a;const c=i[0];let l=r[c];for(let e=1;e<i.length-1;e++){const t=i[e];if(null==l)return;l=l[t]}const d=l[i[i.length-1]];if(d!==s){if(Object.isFrozen(l))return void(n.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:d,newValue:s}));try{l[i[i.length-1]]=s}catch(e){n.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:d,newValue:s,error:e})}}}const Co=new WeakSet;function Eo(e,t,n){const o=e.node,s=e.propSegments;s.length<=1&&j(`Invalid propSegments for web component binding: ${s.join(".")}`);const[r,...i]=s,a=o[r];void 0===a&&j(`Property "${r}" not found on web component.`),a[i.join(".")]=n}function Mo(e,t){const n=dt(t);if(n.pathInfo.path in p){const e=Ie(t.node);return null===e&&j(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&j("ListIndex not found for loopContext:");const n=p[t];void 0===n&&j(`Invalid index name: ${t}`);const o=e.listIndex.at(n);return null===o&&j(`Index not found at position ${n} for loopContext:`),o.index}(e,n.pathInfo.path)}return e[Ce](n)}const Oo=new WeakSet;function Do(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const Ro={class:function(e,t,n){const o=e.node,s=e.propSegments[1];"boolean"!=typeof n&&j("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},attr:function(e,t,n){const o=e.node,s=e.propSegments[1];o.getAttribute(s)!==n&&o.setAttribute(s,n)},style:function(e,t,n){const o=e.propSegments[1],s=e.node.style;s[o]!==n&&(s[o]=n)},command:function(e,t,n){_t(n)||j("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=$n.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||j('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=E(e);if(null===t)return null;const n=M()?.get(t);return void 0===n&&j(`Custom element <${t}> is not defined for command binding.`),D(e)}(r);null===a&&j(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||j(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.`),s&&(s.unsubscribe(),$n.delete(e));const c=new WeakRef(r);let l=null;l=o.subscribe((...t)=>{const n=c.deref();if(!n||!n.isConnected)return l?.(),void $n.delete(e);const o=n[i];return"function"!=typeof o&&j(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),$n.set(e,{token:o,unsubscribe:l,elementRef:c})}},Lo={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!Co.has(t.replaceNode)){Co.add(t.replaceNode);const e=t.replaceNode.parentNode;if(e){const n=t.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);e.insertBefore(o,t.replaceNode),e.insertBefore(s,t.replaceNode.nextSibling)}}},for:function(t,n,o){const s=t.statePathInfo,r=Ye(t),i=Qe(t),a=Pe(i),c=qn(r,a,o);if(n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]),Array.isArray(a)&&a.length===c.deleteIndexSet.size&&c.deleteIndexSet.size>0&&null!==t.node.parentNode){let e=mo.get(t.node);if(void 0===e){const n=fo.get(t.node)||t.node;e=function(e,t){let n=e.previousSibling,o=t.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),mo.set(t.node,e)}if(e){const e=t.node.parentNode;e.textContent="",e.appendChild(t.node)}}for(const e of c.deleteIndexSet){const n=vo(t.node,e);null!==n&&(no(n),n.unmount(),wo(t,n),So(t.node,e,null))}let d=t.node;const u=T(s.path+"."+l),f=n.stateElement.loopContextStack,p=Un(c);let h=null;c.newIndexes.length==c.addIndexSet.size&&c.newIndexes.length>0&&d.isConnected&&(h=document.createDocumentFragment(),Ve(h,n.rootNode));const m=e(),g=t.uuid??"";for(const e of c.newIndexes){let o;if(c.addIndexSet.has(e)){const r=ct(u,e);f.createLoopContext(r,r=>{const i=yo(t);if(o=i.pop(),void 0===o&&(o=uo(t)),null!==h)m&&h.appendChild(document.createComment(`@@wcs-for-start:${g}:${s.path}:${e.index}`)),o.appendTo(h),m&&h.appendChild(document.createComment(`@@wcs-for-end:${g}:${s.path}:${e.index}`));else{if(d.nextSibling!==o.firstNode){if(m){const t=document.createComment(`@@wcs-for-start:${g}:${s.path}:${e.index}`);d.parentNode.insertBefore(t,d.nextSibling),d=t}o.mountAfter(d)}if(m){const t=document.createComment(`@@wcs-for-end:${g}:${s.path}:${e.index}`),n=o.lastNode??d;n.parentNode.insertBefore(t,n.nextSibling)}}to(o,r,n)}),void 0===o&&j(`Content not found for ListIndex: ${e.index} at path "${s.path}"`)}else{if(o=vo(t.node,e),c.changeIndexSet.has(e)){const e=kn(o);for(const t of e)Fo(t,n)}null===o&&j(`Content not found for ListIndex: ${e.index} at path "${s.path}"`);null!==p&&p.has(e)&&No(d,o.firstNode)||d.nextSibling===o.firstNode||o.mountAfter(d)}d=o.lastNode||d,So(t.node,e,o)}fo.set(t.node,d),null!==h&&(t.node.parentNode.insertBefore(h,t.node.nextSibling),Ve(h,null))},if:Ao,else:Ao,elseif:Ao,radio:function(e,t,n){const o=e.node,s=_n(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=_n(o.value,e.inFilters),r=Array.isArray(n)?n:Pn;o.checked=r.includes(s)}},Wo=new WeakMap,Bo=new WeakMap;function jo(e,t){const n=_n(Mo(t.state,e),e.outFilters);if(!0===Bo.get(e))return void t.deferredSelectBindings.push({binding:e,value:n});let o=Wo.get(e);if(void 0===o){if(Wo.has(e))return An(e.replaceNode,t.stateElement)?(o=Eo,Wo.set(e,o)):o=ko,void o(e,t,n);if(o=Lo[e.bindingType],void 0===o){const n=e.propSegments[0];if(o=Ro[n],Wo.set(e,o),void 0===o){E(e.replaceNode)?An(e.replaceNode,t.stateElement)?(o=Eo,Wo.set(e,o)):o=ko:(o=ko,Wo.set(e,o))}}if(o===ko){if("SELECT"===e.node.tagName){const o=e.propSegments[0];if("value"===o||"selectedIndex"===o)return t.deferredSelectBindings.push({binding:e,value:n}),void Bo.set(e,!0)}}o(e,t,n)}else o(e,t,n)}function Fo(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=Qe(e);if(t.updatedAbsAddressSetByStateElement.has(t.stateElement)){t.updatedAbsAddressSetByStateElement.get(t.stateElement).add(n)}else t.updatedAbsAddressSetByStateElement.set(t.stateElement,new Set([n]))}const n=xn(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;const o=E(e.replaceNode);if(o&&void 0===M()?.get(o))return void function(e,t){if(Oo.has(e))return;Oo.add(e);const n=()=>{Oo.delete(e);const t=xn(e);(null===t||t.shouldApplyState(e))&&zo([e])},o=n=>{Oo.delete(e),Do(t,n)},s=xn(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{Oo.delete(e),r()})||(Oo.delete(e),r()))}const r=M();if(null===r)return Oo.delete(e),void Do(t,new Error("CustomElementRegistry is unavailable."));ln(r).wait(t,()=>{e.replaceNode.isConnected?n():Oo.delete(e)},o)}(e,o);if(!0===t.sameRootVerified&&e.stateName===t.stateName)return void jo(e,t);let s=e.replaceNode.getRootNode();if(s instanceof DocumentFragment&&!(s instanceof ShadowRoot)&&(s=He(s),null===s&&j("Root node for fragment not found for binding.")),e.stateName!==t.stateName||s!==t.rootNode){const n=$s(s,e.stateName);null===n&&j(`State element with name "${e.stateName}" not found for binding.`),n.createState("readonly",o=>{const r={stateName:e.stateName,rootNode:s,stateElement:n,state:o,appliedBindingSet:t.appliedBindingSet,newListValueByAbsAddress:t.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:t.updatedAbsAddressSetByStateElement,deferredSelectBindings:t.deferredSelectBindings};jo(e,r)})}else jo(e,t)}function zo(e,t){let o=0;const s=new Set,r=new Map,i=new Map,a=[];for(;o<e.length;){let c=e[o];const l=c.stateName;if(!1===c.replaceNode.isConnected){n.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${c.bindingType} ${c.statePathName} on ${c.node.nodeName}`,c),o++;continue}let d=c.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=He(d),null===d&&j("Root node for fragment not found for binding."));const u=$s(d,l);null===u&&j(`State element with name "${l}" not found for binding.`),u.createState("readonly",n=>{const f={rootNode:d,stateName:l,stateElement:u,state:n,appliedBindingSet:s,newListValueByAbsAddress:r,updatedAbsAddressSetByStateElement:i,deferredSelectBindings:a,sameRootVerified:!0,propagationContextByBinding:t};for(;;){Fo(c,f),o++;const t=e[o];if(!t)break;const n=t.replaceNode.getRootNode();if(t.stateName!==l||n!==f.rootNode)break;c=t}})}for(const{binding:e,value:n}of a)ko(e,{propagationContextByBinding:t},n);for(const[e,t]of r.entries())$e(e,t);for(const[e,t]of i.entries())e.createState("writable",e=>{e[Re](Array.from(t))})}function qo(e,t){const[n,o,s]=ve(e),r=Sn(e);for(const e of n)Ae(e,t);zo(r.initialize(o)),function(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=Se(o);0!==e.length&&(Ae(o.node,t),zo(n.initialize(e)))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}(s,t,r)}const Uo=/\{\{\s*(.+?)\s*\}\}/g,Vo=new Set(["SCRIPT","STYLE"]);function Ho(e){if(!n.enableMustache)return;!function(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[];for(;t.nextNode();)n.push(t.currentNode);for(const e of n)e.parentElement&&Vo.has(e.parentElement.tagName)||Go(e)}(e);const t=Array.from(e.querySelectorAll("template"));for(const e of t)if("http://www.w3.org/2000/svg"===e.namespaceURI){const t=document.createElement("template"),n=Array.from(e.childNodes);for(let e=0;e<n.length;e++){const o=n[e];t.content.appendChild(o)}for(const n of e.attributes)t.setAttribute(n.name,n.value);e.replaceWith(t),Ho(t.content)}else Ho(e.content)}function Go(e){const t=e.data;if(Uo.lastIndex=0,!Uo.test(t))return;Uo.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=Uo.exec(t));){o.index>s&&n.appendChild(document.createTextNode(t.slice(s,o.index)));const e=o[1];n.appendChild(document.createComment(`@@: ${e}`)),s=o.index+o[0].length}s<t.length&&n.appendChild(document.createTextNode(t.slice(s))),e.parentNode.replaceChild(n,e)}let Jo;function Ko(){if(Jo)return Jo;const e=[],t=ne("not",e)(ee);return Jo={filterName:"not",args:e,filterFn:t},Jo}const Yo=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Xo(e,t){const n=t+c+l,o=e.indexOf("|"),s=e.indexOf("@");let r,i;if(-1!==o?(r=e.slice(0,o).trim(),i=e.slice(o)):-1!==s?(r=e.slice(0,s).trim(),i=e.slice(s)):(r=e.trim(),i=""),"."===r)r=n;else{if(!r.startsWith("."))return e;r=n+c+r.slice(1)}return i.length>0?r+i:r}function Qo(e,t){const n=Yo.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+Xo(s,t)+r}function Zo(e,t){const n=e.split(";");let o=!1;const s=n.map(e=>{const n=e.trim();if(0===n.length)return e;const s=n.indexOf(":");if(-1===s)return e;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=Xo(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function es(e,t){return Zo(e,t)}function ts(e,t){const o=n.bindAttributeName,s=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const e=s.currentNode;if(e.nodeType===Node.COMMENT_NODE){const n=e;n.data=Qo(n.data,t);continue}const n=e;if(n instanceof HTMLTemplateElement)continue;const r=n.getAttribute(o);if(null!==r){const e=Zo(r,t);e!==r&&n.setAttribute(o,e)}}}function ns(e){let t=e;const n=[];for(;null!==t.parentNode;){const e=Array.from(t.parentNode.childNodes).indexOf(t);n.unshift(e),t=t.parentNode}return n}function os(e){const t=[],n=ye(e);for(const e of n){const n=be(e);t.push({nodePath:ns(e),parseBindTextResults:n})}return t}function ss(e){const t=Array.from(e.childNodes);for(const n of t)if(n.nodeType===Node.TEXT_NODE){""===(n.textContent||"").trim()&&e.removeChild(n)}}const rs=new Map([["for",n.commentForPrefix],["if",n.commentIfPrefix],["elseif",n.commentElseIfPrefix],["else",n.commentElsePrefix]]),is=Ko();function as(e,t){const n=t.outFilters;return{...t,outFilters:[...n,is],bindingType:e}}function cs(e,t,n,o){ss(t),"string"==typeof o&&ts(t,o),ls(e,t,o);return{fragment:t,parseBindTextResult:n,nodeInfos:os(t)}}function ls(e,t,o){const s=n.commentElsePrefix,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode(e){const t=e;if("template"===t.tagName.toLowerCase()){if((t.getAttribute(n.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let i=null;const a=[],c=[];for(;r.nextNode();){const e=r.currentNode;c.push(e)}for(const t of c){let r=t.getAttribute(n.bindAttributeName)||"";"string"==typeof o&&(r=es(r,o));let c=le(r)[0];const l=rs.get(c.bindingType);if(void 0===l)continue;const d=c.bindingType,u=t.content,f=Mn();let p=null;const h="for"===d?c.statePathName:o;if("else"===d){null===i&&j("'else' binding found without preceding 'if' or 'elseif' binding."),c=as("else",i.parseBindTextResult),p=cs(e,u,c,h),me(f,e,p);const n=a.at(-1),o=document.createComment(`@@${l}:${f}`);void 0!==n?(t.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:ns(o),parseBindTextResults:be(o)})):t.replaceWith(o)}else if("elseif"===d){null===i&&j("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=cs(e,u,c,h),me(f,e,p);const n=document.createComment(`@@${l}:${f}`),o=Mn(),r={fragment:document.createDocumentFragment(),parseBindTextResult:as("else",i.parseBindTextResult),nodeInfos:[]};r.fragment.appendChild(n),r.nodeInfos.push({nodePath:ns(n),parseBindTextResults:be(n)}),me(o,e,r);const d=a.at(-1);a.push(r);const m=document.createComment(`@@${s}:${o}`);void 0!==d?(t.remove(),d.fragment.appendChild(m),d.nodeInfos.push({nodePath:ns(m),parseBindTextResults:be(m)})):t.replaceWith(m)}else{p=cs(e,u,c,h),me(f,e,p);const n=document.createComment(`@@${l}:${f}`);t.replaceWith(n)}"if"===d?(a.length=0,i=p):"elseif"===d?i=p:"else"===d&&(i=null,a.length=0)}}async function ds(e){const t=e.querySelectorAll(n.tagNames.state),o=[];await customElements.whenDefined(n.tagNames.state);for(const e of t){const t=e;o.push(t.initializePromise)}await Promise.all(o)}async function us(e){if(e===document)await ds(document),Ho(document),ls(document,document),qo(document.body,null);else{const t=e;t.host.hasAttribute(n.bindAttributeName)&&await a(t.host),await ds(t),Ho(t),ls(t,t),qo(t,null)}}const fs="1.21.1",ps="undefined"==typeof HTMLElement?class{}:HTMLElement,hs=/^@@wcs-(?:for|if|elseif|else):[^-]/,ms=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,gs=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,bs=/^@@wcs-text-start:(.+)$/;function ys(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class ws extends ps{_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(e){return this.templates.get(e)??null}verifyVersion(){const e=this.version;if(!e)return!0;const t=e.split("."),n=fs.split(".");return t[0]===n[0]&&t[1]===n[1]}setStateData(e){this._stateData=e}setHydrateProps(e){this._hydrateProps=e}_loadStateData(){const e=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}_loadTemplates(){const e=new Map,t=this.querySelectorAll("template[id]");for(const n of t){const t=n.getAttribute("id");t&&e.set(t,n)}return e}_loadHydrateProps(){const e=this.querySelector("script[data-wcs-ssr-props]");if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}static findByName(e,t){const o=n.tagNames.ssr,s=e instanceof Element?e:e instanceof Document?e.documentElement:null;if(!s)return null;return s.querySelector(`${o}[name="${t}"]`)}static extractStateData(e){const t=e.__state;if(!t||"object"!=typeof t)return{};const n={};for(const[e,o]of Object.entries(t))e.startsWith("$")||"function"==typeof o||(n[e]=o);return n}static buildContent(e,t){const o=document.createElement("script");o.setAttribute("type","application/json"),o.textContent=ys(JSON.stringify(t)),e.appendChild(o);const s=Array.from(he.keys());for(const t of s){const o=ge(t);if(!o)continue;const s=document.createElement("template");s.setAttribute("id",t);const r=o.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(n.bindAttributeName,i);const a=o.fragment.cloneNode(!0);s.content.appendChild(a),e.appendChild(s)}const r=Array.from($o);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],o=Po(n);if(0===o.length)continue;const s=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",s);const i={};for(const e of o)i[e.propName]=e.value;t[s]=i}if(Object.keys(t).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=ys(JSON.stringify(t)),e.appendChild(n)}}$o.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(ms.test(e.data)||gs.test(e.data))&&n.push(e)}for(const e of n)e.remove()}static removeStructuralComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;hs.test(e.data)&&n.push(e)}for(const e of n)e.remove()}static restoreTextBindings(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode,o=bs.exec(e.data);o&&n.push({comment:e,path:o[1]})}for(const{comment:e,path:t}of n){const n=document.createComment(`@@: ${t}`);e.parentNode.insertBefore(n,e);let o=e.nextSibling;e.remove();const s=`@@wcs-text-end:${t}`;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=e}}}static cleanupDom(e){const t=document.body,o=e.querySelectorAll(n.tagNames.ssr),s=new Map;for(const e of o){const t=e.querySelectorAll("template[id]");for(const e of t){const t=e.getAttribute("id");t&&s.set(t,e)}}const r=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const e=r.currentNode;ms.test(e.data)&&i.push(e)}for(const e of i){const t=ms.exec(e.data),n=`@@wcs-${t[1]}-end:${t[2]}`;let o=e.nextSibling;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===n){o.remove();break}o.remove(),o=e}e.remove()}ws.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),c=[];for(;a.nextNode();){const e=a.currentNode;if(hs.test(e.data)){const t=e.data.split(":")[1];c.push({comment:e,uuid:t})}}for(const{comment:e,uuid:t}of c){const o=s.get(t);if(o){const t=document.createElement("template"),s=o.getAttribute(n.bindAttributeName);s&&t.setAttribute(n.bindAttributeName,s);const r=document.importNode(o.content,!0);if(r.childNodes.length>0)t.content.appendChild(r);else for(const e of Array.from(o.childNodes))t.content.appendChild(document.importNode(e,!0));e.parentNode.replaceChild(t,e)}}const l=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of l)e.removeAttribute("data-wcs-ssr-id");for(const e of o)e.remove()}}const Ns=new Set(["for","if","elseif","else"]);function vs(e){const t=new vn;if(0===e.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:t};const n=e[0].parentNode,o=e[e.length-1].nextSibling,s=document.createElement("div");for(const t of e)s.appendChild(t);const[r,i]=ve(s),a=t.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:t}}function Ss(e,t,o){const s={for:n.commentForPrefix,if:n.commentIfPrefix,elseif:n.commentElseIfPrefix,else:n.commentElsePrefix}[t];if(!s)return null;const r=`@@${s}:${o}`,i=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const e=i.currentNode;if(e.data===r)return e}return null}function xs(e,t){const o=e;let s=null;for(const[e,r]of t.templates){let t=le(r.getAttribute(n.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&s?t={...s,outFilters:[...s.outFilters,Ko()],bindingType:"else"}:"elseif"===i&&s&&(t={...t,stateName:s.stateName}),"if"===i||"elseif"===i?s=t:"else"===i&&(s=null);const a=document.importNode(r.content,!0),c="for"===i?t.statePathName:void 0;ss(a),"string"==typeof c&&ts(a,c),ls(o,a,c);me(e,o,{fragment:a,parseBindTextResult:t,nodeInfos:os(a)})}}async function Is(e){await ds(e);const t=e.querySelectorAll(n.tagNames.ssr);for(const n of t){const t=n;if(!t.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${t.version}", client="${fs}". Falling back to full render.`),ws.cleanupDom(e),!1}for(const n of t)xs(e,n);const o=function(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const e of o){const n=ms.exec(e.data);if(!n)continue;const o=n[1],s=n[2],r=s.split(":");let i,a,c=null;"for"===o?(i=r[0],a=r[1],c=parseInt(r[2],10)):(i=r[0],a=r.slice(1).join(":"));const l=[];let d=e.nextSibling;const u=`@@wcs-${o}-end:${s}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)l.push(d),d=d.nextSibling;t.push({type:o,uuid:i,path:a,index:c,nodes:l})}return t}(document.body);!function(e,t){const n=new Map;for(const o of t){if(0===o.nodes.length)continue;const t=lo(o.nodes),{bindingInfos:s,subscriberNodes:r,bindingSession:i}=vs(o.nodes);Yn(t,i);for(const e of r)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");Gn(t,s),Zn(t,r);const a=[];for(const e of s)e.statePathName in p&&a.push(e);if(Cn(t,a),"for"===o.type&&null!==o.index){const r=Ss(e,"for",o.uuid);if(r){const e=Rn(null,o.index);go(r,e,t),bo(r,o.nodes[o.nodes.length-1]),ro(r,t),eo(t,ct(T(o.path+"."+l),e)),i.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});let a=n.get(o.uuid);a||(a=[],n.set(o.uuid,a)),a.push(e)}}else{const n=Ss(e,o.type,o.uuid);n&&(ro(n,t),i.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}))}}for(const[t,o]of n){const n=Ss(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=ge(t);if(!r)continue;const i=r.parseBindTextResult.stateName,a=r.parseBindTextResult.statePathName,c=$s(s,i);c&&c.createState("readonly",e=>{const t=e[a];Array.isArray(t)&&Bn(t,o)})}}(document.body,o),ws.removeBlockBoundaryComments(document.body);const s=[];for(const e of t)e.parentNode&&(s.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());ws.restoreTextBindings(document.body);const[r,i]=ve(document.body);for(const e of r)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||(Ae(e,null),t.setAttribute("data-wcs-completed",""))}else Ae(e,null);const a=[],c=[],d=Sn(document.body).initialize(i);for(const e of d)if("event"!==e.bindingType)if(Ns.has(e.bindingType))c.push(e);else{if(e.statePathName.includes(l))continue;a.push(e)}for(const e of c)if("for"===e.bindingType){const t=Qe(e),n=$s(e.replaceNode.getRootNode(),e.stateName);n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&$e(t,o)})}zo(a);for(const{el:e,parent:t,next:n}of s)t.insertBefore(e,n);const u=e.querySelectorAll(n.tagNames.ssr);for(const t of u){const n=t.hydrateProps;for(const[t,o]of Object.entries(n)){const n=e.querySelector(`[data-wcs-ssr-id="${t}"]`);if(n)for(const[e,t]of Object.entries(o))n[e]=t}}const f=e.querySelectorAll("[data-wcs-completed]");for(const e of f)e.removeAttribute("data-wcs-completed");return!0}const As=new WeakMap,_s=new WeakMap,Ps=new Set;function $s(e,t){let n=As.get(e);return n&&n.get(t)||null}function Ts(e){return _s.get(e)??Promise.resolve()}function ks(t,o,s){let r=As.get(t);if(null===s){if(!r)return;const e=r.get(o);r.delete(o),0===r.size&&As.delete(t),void 0!==e&&(Ps.delete(e),null!==et&&et({type:"state:element-unregistered",name:o,rootNode:t,element:e})),n.debug&&console.debug(`State element unregistered: name="${o}"`)}else{if(!r){r=new Map,As.set(t,r);const n=!e()&&s.hasAttribute?.("enable-ssr");if("HTMLDocument"===t.constructor.name||"Document"===t.constructor.name){const e=new Promise(e=>{queueMicrotask(async()=>{if(n){await Is(t)||await us(t)}else await us(t);e()})});_s.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise(e=>{queueMicrotask(async()=>{await us(t),e()})});_s.set(t,e)}}r.has(o)&&j(`State element with name "${o}" is already registered.`),r.set(o,s),Ps.add(s),null!==et&&et({type:"state:element-registered",name:o,rootNode:t,element:s}),n.debug&&console.debug(`State element registered: name="${o}"`,s)}}const Cs=new Set;function Es(e){Cs.add(e)}const Ms=new class{_queueUpdateRecords=[];constructor(){}enqueueAbsoluteAddress(e,t=null){const n=0===this._queueUpdateRecords.length;this._queueUpdateRecords.push({absoluteAddress:e,context:t}),n&&queueMicrotask(()=>{const e=this._queueUpdateRecords;this._queueUpdateRecords=[],this._applyChange(e)})}testApplyChange(e,t){this._applyChange(e.map((e,n)=>({absoluteAddress:e,context:t?.[n]??null})))}_applyChange(e){const t=new Map;for(const n of e){const e=t.get(n.absoluteAddress);null!==et&&null!=e&&null!==n.context&&e.transactionId!==n.context.transactionId&&et({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:e.transactionId,winnerTransactionId:n.context.transactionId}),t.set(n.absoluteAddress,n.context)}const n=[],o=new Map;for(const[e,s]of t){if(null!==s&&s.hop>=32){console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:e.absolutePathInfo.pathInfo.path,stateName:e.absolutePathInfo.stateName,transactionId:s.transactionId,hop:s.hop,maxHops:32}),null!==et&&et({type:"propagation:hop-limit",absoluteAddress:e,transactionId:s.transactionId,hop:s.hop});continue}const t=nt(e);if(void 0!==t)for(const e of t)!1!==e.replaceNode.isConnected&&(n.push(e),null!==s&&o.set(e,s))}o.size>0?zo(n,o):zo(n),function(e){for(const t of Cs)t(e)}(new Set(t.keys()))}};function Os(){return Ms}const Ds="__WCSTACK_DEVTOOLS_HOOK__";function Rs(){const e=globalThis,t=e[Ds];if(void 0!==t)return 1!==t.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${t.version}, expected 1. Keeping the existing registry (first-wins).`),t;const n=function(){const e=new Map,t=new Set,n=e=>{if(0===t.size)return void e._setSink(null);const n=e.id;e._setSink(e=>{for(const o of t)o.onEvent?.(n,e)})};return{version:1,sources:e,register(o){if(!e.has(o.id)){e.set(o.id,o),n(o);for(const e of t)e.onSourceRegistered?.(o)}},unregister(n){const o=e.get(n);if(void 0!==o){o._setSink(null),e.delete(n);for(const e of t)e.onSourceUnregistered?.(n)}},addListener(o){t.add(o);for(const t of e.values())n(t),o.onSourceRegistered?.(t);return()=>{if(t.delete(o))for(const t of e.values())n(t)}}}}();return e[Ds]=n,n}const Ls=e=>{null!==et&&et({type:"state:update-batch",addresses:e})};function Ws(e){const t=null!==et;!function(e){et=e}(e);const n=null!==e;var o;n&&!t?Es(Ls):!n&&t&&(o=Ls,Cs.delete(o))}function Bs(e){return{name:e.name,rootNode:e.rootNode,element:e,paths:{list:e.listPaths,element:e.elementPaths,getter:e.getterPaths,setter:e.setterPaths},commandTokenNames:e.commandTokenNames,eventTokenNames:e.eventTokenNames,staticDependency:e.staticDependency,dynamicDependency:e.dynamicDependency}}function js(e,t){return $s(t,e)??j(`devtools: state element not found: name="${e}"`)}let Fs=null;function zs(){if(e())return;if(null!==Fs)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:fs,getStateElements(){const e=[];for(const t of Ps)e.push(Bs(t));return e},keys(e,t){const n=js(e,t),o=[];return n.createState("readonly",e=>{for(const t of Object.keys(e))if(!t.includes("*")&&!t.startsWith("$")){try{if("function"==typeof e[t])continue}catch{}o.push(t)}}),o},read(e,t,n,o){let s;return js(e,t).createState("readonly",e=>{s=e.$resolve(n,o??[])}),s},write(e,t,n,o,s){js(e,t).createState("writable",e=>{void 0!==s&&s.length>0?e.$resolve(n,s,o):e[n]=o})},_setSink:Ws};Fs=t,Rs().register(t)}async function qs(e,t){let n=null;const o=`\n//# sourceURL=${t}\n`;if("function"==typeof URL.createObjectURL){const t=new Blob([e.text+o],{type:"application/javascript"}),s=URL.createObjectURL(t);try{n=await import(s)}finally{URL.revokeObjectURL(s)}}else{const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(e.text+o)));n=await import(`data:application/javascript;base64,${t}`)}return n&&"object"==typeof n.default?n.default:{}}async function Us(e){try{return(await import(e)).default||{}}catch(e){j(`Failed to load script file: ${e}`)}}class Vs{_loopContextStack=Array(d).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&j("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=d&&j("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&&j("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const e=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==e&&j("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else n.listIndex.length!==n.pathInfo.wildcardCount&&j(`Cannot push loop context when there is no active loop context: the list index chain (length ${n.listIndex.length}) does not cover the wildcard path (wildcard count ${n.pathInfo.wildcardCount}).`);let s;this._loopContextStack[this._length]=n,this._length++;try{s=t(n)}finally{s instanceof Promise?s.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return s}}const Hs=new WeakMap;function Gs(e,t){let n=Hs.get(e);void 0===n&&(n=new Map,Hs.set(e,n));let o=n.get(t);return void 0===o&&(o=new At(t,e.name),n.set(t,o)),o}const Js=new WeakMap;function Ks(e){const t=Js.get(e);if(void 0!==t)return t;const n=new Proxy(Object.create(null),{get(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return Gs(e,n)},has:(t,n)=>"string"==typeof n&&e.commandTokenNames.has(n),ownKeys:()=>Array.from(e.commandTokenNames),getOwnPropertyDescriptor(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:Gs(e,n)}},set(){j("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){j("$command namespace is read-only; deleting from it is not allowed.")}});return Js.set(e,n),n}const Ys=Symbol("wcs-stream-last-notified-uncertain"),Xs=new WeakMap;function Qs(e,t){const n=Xs.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function Zs(e,t){const n=Xs.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:Ys,error:Object.is(o.error,null)?null:Ys})}const er=new Set;function tr(e){er.delete(e)}function nr(){return er}const or=new WeakMap;function sr(e){return or.get(e)??new Map}function rr(e){tr(e);const t=or.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Zs(e,n.name)}const ir=(e,t)=>t,ar=new Set;function cr(e,t){const n=t[x];if(void 0===n)return void Qs(e,ar);"object"==typeof n&&null!==n||j(`${x} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[s,r]of Object.entries(n)){0===s.length&&j(`${x} entry name must be a non-empty string.`),s.includes(c)&&j(`${x} entry "${s}" must be a flat property name ("${c}" is not allowed).`),s.includes(l)&&j(`${x} entry "${s}" must be a flat property name ("${l}" is not allowed).`),s.startsWith("$")&&j(`${x} entry "${s}" must not start with "$" (reserved namespace).`),s in Object.prototype&&j(`${x} entry "${s}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(s)&&j(`${x} entry "${s}" conflicts with a getter declared on the state.`),e.setterPaths.has(s)&&j(`${x} entry "${s}" conflicts with a setter declared on the state.`),"object"==typeof r&&null!==r||j(`${x} entry "${s}" must be an object ({ args?, source, fold?, initial? }).`);const n=r;"function"!=typeof n.source&&j(`${x} entry "${s}" source must be a function.`);const i=void 0!==n.fold;i&&"function"!=typeof n.fold&&j(`${x} entry "${s}" fold must be a function.`),i&&!("initial"in n)&&j(`${x} entry "${s}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&j(`${x} entry "${s}" args must be a function.`);const a={name:s,definition:{args:n.args??null,source:n.source,fold:n.fold??ir,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};s in t||(t[s]=a.definition.initial),o.set(s,a)}!function(e,t){or.set(e,t)}(e,o),Qs(e,new Set(o.keys()))}const lr=new WeakMap,dr=new WeakMap;function ur(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=sr(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&sr(e).has(n),ownKeys:()=>Array.from(sr(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=sr(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){j(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){j(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function fr(e){const t=lr.get(e);if(void 0!==t)return t;const n=ur(e,I,e=>e.status);return lr.set(e,n),n}function pr(e){const t=dr.get(e);if(void 0!==t)return t;const n=ur(e,A,e=>e.error);return dr.set(e,n),n}function hr(e){lr.delete(e),dr.delete(e)}let mr=null;async function gr(e,t,n,o){let s=null,r=null;const i=()=>{if(s&&s!==r){r=s;try{s.return?.()?.then?.(void 0,()=>{})}catch{}}};n.addEventListener("abort",i,{once:!0});try{const r=await e(t,n);if(s=function(e,t){if("function"==typeof e?.[Symbol.asyncIterator])return e;if("function"!=typeof e?.getReader)throw new TypeError("[@wcstack/state] $streams: source must return an AsyncIterable or a ReadableStream (got neither).");return async function*(e,t){const n=e.getReader(),o=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",o,{once:!0});try{for(;;){const{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t.removeEventListener("abort",o),n.releaseLock()}}(e,t)}(r,n)[Symbol.asyncIterator](),n.aborted)return void i();for(;;){const e=await s.next();if(e.done)break;if(n.aborted)return;o.fold(e.value)}if(n.aborted)return;o.done()}catch(e){if(n.aborted)return;o.fail(e)}finally{n.removeEventListener("abort",i)}}function br(e){const t=sr(e);if(0!==t.size){!function(e){er.add(e)}(e);for(const n of t.values())yr(e,n)}}function yr(e,t){t.controller?.abort();const n=new AbortController;t.controller=n;const o=function(e,t){const n=t.definition.args;if(null===n)return void t.depAddresses.clear();const o=mr,s=new Set;let r;mr=s;try{e.createState("readonly",e=>{r=n(e)})}finally{mr=o}r instanceof Promise&&j(`${x} entry "${t.name}" args must be synchronous (it returned a Promise).`);const i=`${I}${c}${t.name}`,a=`${A}${c}${t.name}`;for(const n of s){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==e||o.path!==t.name&&o.path!==i&&o.path!==a||j(`${x} entry "${t.name}" args must not read the stream itself ("${o.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),o.wildcardCount>0&&j(`${x} entry "${t.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return t.depAddresses=s,r}(e,t);e.createState("writable",e=>{e[t.name]=t.definition.initial}),wr(e,t,"active",null);const s=t.definition,r={fold(n){e.createState("writable",e=>{e[t.name]=s.fold(e[t.name],n)})},done(){wr(e,t,"done",null)},fail(o){wr(e,t,"error",o),n.abort()}};gr(s.source,o,n.signal,r)}function wr(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return Xs.get(e)?.get(t)??{status:"idle",error:null}}(e,t.name),r=s.status!==n,i=!Object.is(s.error,o);(r||i)&&(!function(e,t,n,o){let s=Xs.get(e);void 0===s&&(s=new Map,Xs.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{r&&e.$postUpdate(`${I}${c}${t.name}`),i&&e.$postUpdate(`${A}${c}${t.name}`)}))}function Nr(e){return function(){const t=this.stateElement;if(!t)return;let n;try{t.createState("readonly",t=>{n=t[e]})}catch(t){return void console.warn(`[@wcstack/state] DCC getter "${e}" failed:`,t)}return n}}function vr(e){return function(t){const n=this.stateElement;n&&n.initializePromise.then(()=>{n.createState("writable",n=>{n[e]=t})})}}function Sr(e,t){return t?function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[e](...t)}).then(()=>o)})}:function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[e](...t)}),o})}}function xr(e){return e.startsWith("$")}Es(function(e){const t=nr();if(0===t.size)return;const n=[];for(const o of t)for(const t of sr(o).values())for(const s of t.depAddresses)if(e.has(s)){n.push({stateElement:o,entry:t});break}for(const{stateElement:e,entry:o}of n)if(t.has(e)&&sr(e).get(o.name)===o)try{yr(e,o)}catch(n){o.controller?.abort(),t.has(e)&&sr(e).get(o.name)===o&&wr(e,o,"error",n)}});const Ir=new Map;class Ar{path;segments;paths;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(e){const t=e.split("."),n=t.slice(),o=[];let s=0,r=0,i="",a=0,c="none";const l=[];for(let e=0;e<t.length;e++){const c=t[e];if("*"===c)n[e]="*",l.push(null),s++,a++;else{const t=Number(c);Number.isNaN(t)||(n[e]="*",l.push(t),r++,a++)}i+=c,o.push(i),i+=e<c.length-1?".":""}const d=T(n.join("."));(s>0||r>0)&&(c=s===a?"context":r===a?"all":"partial"),this.path=e,this.segments=t,this.paths=o,this.wildcardCount=a,this.wildcardType=c,this.wildcardIndexes=l,this.pathInfo=d}}function _r(e){let t;return Ir.get(e)??(Ir.set(e,t=new Ar(e)),t)}const Pr=new WeakMap;function $r(e,t){null===t?Pr.delete(e):Pr.set(e,t)}function Tr(e){const t=Pr.get(e);t&&(t.dirty=!0)}function kr(e,t){let n=e;for(let e=1;e<t.length;e++){if(Object(n)!==n)return;n=Reflect.get(n,t[e])}return n}function Cr(e,t,n,o,s){const r=t.pathInfo.segments[0];if(r===N)return kr(Ks(s),t.pathInfo.segments);if(r===I)return kr(fr(s),t.pathInfo.segments);if(r===A)return kr(pr(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){const s=Mr(e,t.parentAddress??j(`address.parentAddress is undefined path: ${t.pathInfo.path}`),n,o),r=t.pathInfo.segments[t.pathInfo.segments.length-1];if(r===l){const e=t.listIndex?.index??j(`address.listIndex?.index is undefined path: ${t.pathInfo.path}`);return Reflect.get(s,e)}return Reflect.get(s,r)}if(!s.getterPaths.has(t.pathInfo.path))return Reflect.get(e,t.pathInfo.path);o.pushAddress(t);try{return Reflect.get(e,t.pathInfo.path,n)}finally{o.popAddress()}}function Er(e,t,n,o,s){const r=qe(We(s,t.pathInfo),t.listIndex),i=function(e){return Pr.get(e)??null}(r);if(null!==i&&!1===i.dirty)return i.value;const a=Cr(e,t,n,o,s);return $r(r,{value:a,dirty:!1}),a}function Mr(e,t,n,o){!function(e,t){if(e.addressStackLength>0){const n=e.lastAddressStack,o=n?.pathInfo??null,s=e.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==t.pathInfo.path&&(s.addDynamicDependency(t.pathInfo.path,o.path),t.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const e=Je(t.pathInfo,o);if(e>0){let o=!1;for(let s=0;s<e;s++)if(t.listIndex?.at(s)!==n.listIndex?.at(s)){o=!0;break}if(o)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}(o,t),function(e,t){if(null===mr)return;const n=We(e,t.pathInfo);mr.add(qe(n,t.listIndex))}(o.stateElement,t);const s=o.stateElement;return t.pathInfo.wildcardCount>0||s.getterPaths.has(t.pathInfo.path)?Er(e,t,n,o,s):Cr(e,t,n,o,s)}function Or(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[t];return void 0===o?null:n.listIndex?.at(o)??null}function Dr(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=Mr(e,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=t.pathInfo.lastSegment;if(i===l){const e=t.listIndex?.index;return"number"==typeof e&&e in r}return i in r}const Rr=new WeakMap;function Lr(e,t){null===t?Rr.delete(e):Rr.set(e,t)}function Wr(e,t,o){const s=T(e.wildcardParentPaths[t]),r=We(e.stateElement,s),i=ct(s,o),a=Pe(qe(r,o)),c=e.stateProxy[Ce](i),l=function(e,t){switch(t){case"old":return e.oldIndexes;case"new":return e.newIndexes;case"add":return e.addIndexSet;case"change":return e.changeIndexSet;case"delete":return e.deleteIndexSet;default:return n.debug&&console.log(`Invalid search type: ${t}`),[]}}(qn(i.listIndex,a,c),e.searchType);if(t===e.wildcardPaths.length-1)e.targetListIndexes.push(...l);else for(const n of l)Wr(e,t+1,n)}function Br(e,t,n,o,s){return"full"===e.listExpansion||e.stateElement.crossRowListPaths?.has(t)?s.newIndexes:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?s.newIndexes:s.changeIndexSet:0===s.addIndexSet.size?s.changeIndexSet:0===s.changeIndexSet.size?s.addIndexSet:[...s.addIndexSet,...s.changeIndexSet]}function jr(e,t,n,o,s,r,i,a,c,d){const u={stateElement:t,staticMap:o,dynamicMap:s,result:new Set,listPathSet:r,visited:new Set,stateProxy:i,searchType:a,listExpansion:d?.listExpansion??"full"};return function(e,t,n){const o=[{address:t,depth:0}];for(;o.length>0;){const{address:t,depth:s}=o.pop();if(s>1e3&&j(`Maximum dependency depth of 1000 exceeded. Possible circular dependency detected at path: ${t.pathInfo.path}`),e.visited.has(t))continue;e.visited.add(t),n(t);const r=t.pathInfo.path,i=s+1,a=[],c=e.staticMap.get(r);if(c)for(const n of c){const o=T(n);if(e.listPathSet.has(r)&&o.lastSegment===l){const n=e.stateProxy[Ce](t),s=Pe(qe(We(e.stateElement,t.pathInfo),t.listIndex)),c=qn(t.listIndex,s,n);for(const t of Br(e,r,0,0,c)){const n=ct(o,t);e.result.add(n),a.push({address:n,depth:i})}}else{const n=ct(o,t.listIndex);e.result.add(n),a.push({address:n,depth:i})}}const d=e.dynamicMap.get(r);if(d)for(const n of d){const o=T(n),s=[];if(o.wildcardCount>0){const n=Je(t.pathInfo,o);if(o.wildcardCount-n>=1){let r;n>0?(null===t.listIndex&&j(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),r=t.listIndex.at(n-1)):r=null;const i={stateElement:e.stateElement,targetListIndexes:[],wildcardPaths:o.wildcardPaths,wildcardParentPaths:o.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};Wr(i,n,r),s.push(...i.targetListIndexes)}else{null===t.listIndex&&j(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=t.listIndex.at(n-1);s.push(e)}}else s.push(null);for(const t of s){const n=ct(o,t);e.result.add(n),a.push({address:n,depth:i})}}for(let e=a.length-1;e>=0;e--)o.push(a[e])}}(u,n,c),Array.from(u.result)}function Fr(e,t,o,s,r,i){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,s);const o=Mr(e,n,r,i),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===l){const e=t.listIndex?.index??j(`address.listIndex?.index is undefined path: ${t.pathInfo.path}`);return Reflect.set(o,e,s)}return Reflect.set(o,a,s)}if(!i.stateElement.setterPaths.has(t.pathInfo.path))return Reflect.set(e,t.pathInfo.path,s);i.pushAddress(t);try{return Reflect.set(e,t.pathInfo.path,s,r)}finally{i.popAddress()}}finally{const e=n.enablePropagationContext?Kt()??Ht(-1):null,s=Os();s.enqueueAbsoluteAddress(o,e),jr(i.stateName,i.stateElement,t,i.stateElement.staticDependency,i.stateElement.dynamicDependency,i.stateElement.listPaths,r,"new",n=>{if(n===t)return;const o=qe(We(i.stateElement,n.pathInfo),n.listIndex);Tr(o),s.enqueueAbsoluteAddress(o,e)},{listExpansion:"diff"})}}function zr(e,t,n,o,s,r){let i=t.parentAddress??j(`address.parentAddress is undefined path: ${t.pathInfo.path}`),a=function(e){return Rr.get(e)??null}(i);if(null===a){const t=Mr(e,i,s,r)??[],n=Wn(t)??[];a={value:[...t],listIndexes:[...n]},Lr(i,a)}try{return Fr(e,t,n,o,s,r)}finally{const n=a.value.indexOf(o),c=Mr(e,i,s,r)??[],l=Array.isArray(c)?Wn(c)??[]:[],d=t.listIndex.index,u=-1!==n?a.listIndexes[n]:Rn(i.listIndex,-1);l[d]=u;if(new Set(c).size===a.value.length){for(let e=0;e<l.length;e++)l[e].index=e;Lr(i,null)}}}function qr(e,t,o,s,r){const i=r.stateElement;let a,c=!1;if(n.sameValueGuard&&(null===o||"object"!=typeof o)){const n=Mr(e,t,s,r);if(Dr(e,t,s,r)&&Object.is(n,o))return!0;a=n,c=!0}const l=i.elementPaths.has(t.pathInfo.path),d=t.pathInfo.wildcardCount>0||i.getterPaths.has(t.pathInfo.path),u=qe(We(i,t.pathInfo),t.listIndex);null!==et&&et({type:"state:write",absoluteAddress:u,value:o,oldValue:a,hasOldValue:c});try{return l?zr(e,t,u,o,s,r):Fr(e,t,u,o,s,r)}finally{d&&$r(u,{value:o,dirty:!1});const e=i.bindableEventMap[t.pathInfo.path];if(e){const t=i.rootNode;t instanceof ShadowRoot&&t.host.dispatchEvent(new CustomEvent(e,{detail:o,bubbles:!0}))}}}function Ur(e,t,n,o){return(t,s,r)=>{const i=T(t);if(o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}i.wildcardParentPathInfos.length>s.length&&j(`indexes length is insufficient: ${t}`);let a=null;for(let t=0;t<i.wildcardParentPathInfos.length;t++){const r=i.wildcardParentPathInfos[t],c=ct(r,a),l=Wn(Mr(e,c,n,o));null==l&&j(`ListIndexes not found: ${r.path}`);a=l[s[t]]??j(`ListIndex not found: ${r.path}`)}const c=ct(i,a);if(!(void 0!==r))return Mr(e,c,n,o);qr(e,c,r,n,o)}}const Vr=new WeakMap;function Hr(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return Or(o,s.wildcardPaths.at(-1)??j(`lastWildcardPath is null: ${t.pathInfo.path}`))??j(`ListIndex not found: ${t.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<t.pathInfo.wildcardCount;r++){const i=t.pathInfo.wildcardParentPathInfos[r]??j(`wildcardParentPathInfo is null: ${t.pathInfo.path}`);s=(Wn(Mr(e,ct(i,s),n,o))??j(`ListIndex not found: ${i.path}`))[t.wildcardIndexes[r]??j(`wildcardIndex is null: ${t.pathInfo.path}`)]??j(`ListIndex not found: ${i.path}`)}return s}case"partial":j(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function Gr(e,t,n){void 0!==e.loopContext&&j("already in loop context"),e.setLoopContext(t);try{e.pushAddress(t);try{return n()}finally{e.popAddress()}}finally{e.clearLoopContext()}}const Jr=`${I}${c}`,Kr=`${A}${c}`;function Yr(e,t,n,o){const s=p[t];if(void 0!==s){0===o.addressStackLength&&j(`No active state reference to get list index for "${t.toString()}".`);const e=o.lastAddressStack?.listIndex;return e?.indexes[s]??j(`ListIndex not found: ${t.toString()}`)}if("string"==typeof t){if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>function(e,t,n,o){const s=Ur(e,0,n,o);return(t,r)=>{const i=new Map,a=T(t);if(o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==a.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(a.path,e.path)}if(void 0===r){for(let e=0;e<a.wildcardParentPathInfos.length;e++){const t=a.wildcardParentPathInfos[e],n=Or(o,t.path);if(n){r=n.indexes;break}}void 0===r&&(r=[])}const c=(t,s,r,a,l,d,u)=>{const f=t[s]??null;if(null===f)return void u.push(d);const p=ct(f,r),h=Vr.get(p),m=Mr(e,p,n,o),g=qn(r,h,m).newIndexes,b=a[l]??null;if(i.set(p,m),null===b)for(let e=0;e<g.length;e++){const n=g[e];c(t,s+1,n,a,l+1,d.concat(n.index),u)}else{const e=g[b]??j(`ListIndex not found: ${f.path}`);s+1<t.length?c(t,s+1,e,a,l+1,d.concat(e.index),u):u.push(d.concat(e.index))}},l=[];c(a.wildcardParentPathInfos,0,null,r,0,[],l);const d=[];for(let e=0;e<l.length;e++)d.push(s(a.path,l[e]));for(const[e,t]of i.entries())Vr.set(e,t);return d}}(e,0,n,o)(t,s);case"$postUpdate":return t=>function(e,t,n,o){const s=o.stateElement;return t=>{const r=_r(t),i=Hr(e,r,n,o),a=ct(r.pathInfo,i),c=qe(We(s,a.pathInfo),a.listIndex),l=Os();l.enqueueAbsoluteAddress(c),jr(o.stateName,o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=qe(We(s,e.pathInfo),e.listIndex);Tr(t),l.enqueueAbsoluteAddress(t)})}}(e,0,n,o)(t);case"$resolve":return(t,s,r)=>Ur(e,0,n,o)(t,s,r);case"$trackDependency":return e=>function(e,t,n,o){return e=>{0===o.addressStackLength&&j(`No active state reference to track dependency for path "${e}".`);const t=o.lastAddressStack?.pathInfo??j("Internal error: lastAddressStack is null"),n=o.stateElement;o.stateElement.getterPaths.has(t.path)&&t.path!==e&&n.addDynamicDependency(e,t.path)}}(0,0,0,o)(e);case N:return Ks(o.stateElement);case I:return fr(o.stateElement);case A:return pr(o.stateElement)}if(!t.startsWith(Jr)&&!t.startsWith(Kr))return}const s=_r(t),r=Hr(e,s,n,o),i=ct(s.pathInfo,r);return Mr(e,i,n,o)}if("symbol"==typeof t){switch(t){case Te:return(e,t=async()=>{})=>async function(e,t,n){return await Gr(e,t,n)}(o,e,t);case ke:return(e,t=()=>{})=>function(e,t,n){return Gr(e,t,n)}(o,e,t);case Ce:return t=>Mr(e,t,n,o);case Ee:return t=>Dr(e,t,n,o);case Me:return(t,s)=>qr(e,t,s,n,o);case Oe:return()=>async function(e,t,n){const o=Reflect.get(e,h);"function"==typeof o&&await o.call(n)}(e,0,n);case De:return()=>function(e,t,n){const o=Reflect.get(e,m);"function"==typeof o&&o.call(n)}(e,0,n);case Re:return t=>function(e,t,n,o){const s=Reflect.get(e,g);if("function"==typeof s){const e=new Set,r={};for(const n of t){const t=n.absolutePathInfo.pathInfo;let s;if(s=n.absolutePathInfo.stateName===o.stateName?t.path:t.path+"@"+n.absolutePathInfo.stateName,e.add(s),t.wildcardCount>0){const e=n.listIndex.indexes??[],t=r[s];void 0===t?r[s]=[e]:t.push(e)}}return s.call(n,Array.from(e),r)}}(e,t,n,o)}return Reflect.get(e,t,n)}}class Xr{_stateElement;_stateName;_addressStack=Array(d).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;constructor(e,t,n){this._stateName=t;const o=$s(e,this._stateName);null===o&&j(`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 e;return this._addressStackIndex>=0&&(e=this._addressStack[this._addressStackIndex]),void 0===e&&j("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex++,this._addressStackIndex>=d&&j("Exceeded maximum address stack depth of 128. Possible infinite loop."),this._addressStack[this._addressStackIndex]=e}popAddress(){if(this._addressStackIndex<0)return null;const e=this._addressStack[this._addressStackIndex];return void 0===e&&j(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,e}setLoopContext(e){this._loopContext=e}clearLoopContext(){this._loopContext=void 0}get(e,t,n){return Yr(e,t,n,this)}set(e,t,n,o){return"readonly"===this._mutability&&j(`State "${this._stateName}" is readonly.`),function(e,t,n,o,s){if("string"==typeof t){const r=_r(t),i=Hr(e,r,o,s);return qr(e,ct(r.pathInfo,i),n,o,s)}return Reflect.set(e,t,n,o)}(e,t,n,o,this)}has(e,t){return Reflect.has(e,t)}}const Qr=new WeakMap;const Zr=new WeakMap;function ei(e,t){const n=Zr.get(e);return n?n.get(t)??null:null}const ti=new WeakMap,ni=new WeakMap,oi=new WeakMap,si=new WeakMap;function ri(e,t){return{innerAbsPathInfo:We(e,T(t.propSegments.slice(1).join(c))),outerAbsPathInfo:Qe(t).absolutePathInfo}}function ii(e,t){let n=ti.get(e);if(void 0===n&&(n=new Map,ti.set(e,n)),n.has(t))return n.get(t);let o=ni.get(e);void 0===o&&(o=new Map,ni.set(e,o));const s=oi.get(e);if(void 0===s)return null;let r=null;for(const e of s)if(t.pathInfo.cumulativePathInfoSet.has(e.innerAbsPathInfo.pathInfo)){e.innerAbsPathInfo.pathInfo.segments.length===t.pathInfo.segments.length&&j("Duplicate mapping rule for web component."),r=e;break}if(null===r)return null;const i=si.get(r);void 0===i&&j("Binding not found for primary mapping rule on web component.");const a=t.pathInfo.segments.slice(r.innerAbsPathInfo.pathInfo.segments.length),l=T(r.outerAbsPathInfo.pathInfo.segments.concat(a).join(c)),d=$s(e.getRootNode(),i.stateName);null===d&&j(`State element with name "${i.stateName}" not found for web component.`);const u=We(d,l);n.set(t,u),o.set(u,t);return function(e,t){const n=V(e);null===n?H(e,[t]):n.push(t)}(e,{...i,propName:t.pathInfo.path,propSegments:t.pathInfo.segments,statePathName:u.pathInfo.path,statePathInfo:u.pathInfo}),u}function ai(e){return function(e){const t=Object.getPrototypeOf(e),n=Object.create(t),o=Object.getOwnPropertyDescriptors(e);for(const e in o){const t=o[e];!1===t.writable&&(t.writable=!0)}return Object.defineProperties(n,o),n}(e)}class ci{_webComponent;_innerStateElement;constructor(e,t){this._webComponent=e,this._innerStateElement=ei(e,t)??j("State element not found for web component.")}get(e,t,n){if("string"!=typeof t)return Reflect.get(e,t,n);{if("then"===t)return;if("$"===t[0])return;if(this._innerStateElement.getterPaths.has(t)&&t in e)return Reflect.get(e,t,n);const o=T(t),s=We(this._innerStateElement,o),r=ii(this._webComponent,s);if(null!==r){const e=Ie(this._webComponent);let t;return r.stateElement.createState("readonly",n=>{n[ke](e,()=>{t=n[r.pathInfo.path];let o=null;null!==e&&null!==e.listIndex&&r.pathInfo.wildcardCount>0&&(o=e.listIndex.at(r.pathInfo.wildcardCount-1));!function(e,t){Qr.set(e,t)}(qe(r,o),t)})}),t}if(t in e)return Reflect.get(e,t,n);j(`Property "${t}" not found in inner state: no mapping rule and no local state property.`)}}set(e,t,n,o){if("string"!=typeof t)return Reflect.set(e,t,n,o);{if(this._innerStateElement.setterPaths.has(t)&&t in e)return Reflect.set(e,t,n,o);const s=T(t),r=We(this._innerStateElement,s),i=ii(this._webComponent,r);if(null!==i){const e=Ie(this._webComponent);return i.stateElement.createState("writable",t=>{t[ke](e,()=>{t[i.pathInfo.path]=n})}),!0}if(t in e)return Reflect.set(e,t,n,o);j(`Property "${t}" not found in inner state: no mapping rule and no local state property.`)}}has(e,t){if("string"==typeof t){if("$"===t[0])return!1;if((this._innerStateElement.getterPaths.has(t)||this._innerStateElement.setterPaths.has(t))&&t in e)return!0;const n=T(t),o=We(this._innerStateElement,n);return null!==ii(this._webComponent,o)||t in e}return Reflect.has(e,t)}}class li{_innerStateElement;constructor(e,t){this._innerStateElement=ei(e,t)??j("State element not found for web component.")}get(e,t,n){if("string"==typeof t){const e=T(t),n=qe(We(this._innerStateElement,e),null);return o=n,Qr.get(o)}return Reflect.get(e,t,n);var o}set(e,t,n,o){if("string"==typeof t){const e=T(t),n=We(this._innerStateElement,e);return this._innerStateElement.createState("readonly",e=>{e.$postUpdate(n.pathInfo.path)}),!0}return Reflect.set(e,t,n,o)}}class di{_innerStateElement;constructor(e,t){this._innerStateElement=ei(e,t)??j("State element not found for web component.")}get(e,t,n){if("string"==typeof t){let e;return this._innerStateElement.createState("readonly",n=>{e=n[t]}),e}return Reflect.get(e,t,n)}set(e,t,n,o){return"string"==typeof t?(this._innerStateElement.createState("writable",e=>{e[t]=n}),!0):Reflect.set(e,t,n,o)}}const ui=e=>()=>e;function fi(e,t,o,s){if(function(e,t,n){let o=Zr.get(e);o||(o=new Map,Zr.set(e,o)),o.set(t,n)}(t,o,e),t.hasAttribute(n.bindAttributeName)){const n=(V(t)??[]).filter(e=>e.propSegments[0]===o);!function(e,t,n){if(0===n.length)return;const o=ei(e,t);null===o&&j("State element not found for web component.");const s=new Map,r=new Map;for(const t of n){const n=ri(o,t);let i=oi.get(e);void 0===i?oi.set(e,new Set([n])):i.add(n);const a=n.innerAbsPathInfo,c=n.outerAbsPathInfo;si.set(n,t),s.set(a,c),r.set(c,a)}ti.set(e,s),ni.set(e,r)}(t,o,n);const s=function(e,t){const n=new li(e,t);return new Proxy({},n)}(t,o),r=function(e,t){const n=new ci(e,t),o=ei(e,t);null===o&&j("State element not found for web component."),null===o.boundComponentStateProp&&j("State element is not bound to any component state prop."),o.boundComponentStateProp in e||j(`State element is not bound to a valid component state prop: ${o.boundComponentStateProp}`);const s=e[o.boundComponentStateProp];return"object"==typeof s&&null!==s||j(`Invalid state object for component state prop: ${o.boundComponentStateProp}`),new Proxy(ai(s),n)}(t,o);e.setInitialState(r),Object.defineProperty(t,o,{get:ui(s),enumerable:!0,configurable:!0})}else{e.setInitialState(ai(s));const n=function(e,t){const n=new di(e,t);return new Proxy({},n)}(t,o);Object.defineProperty(t,o,{get:ui(n),enumerable:!0,configurable:!0})}if(function(e,t){let n=In.get(e);n||(n=new WeakMap,In.set(e,n)),n.set(t,!0)}(t,e),b in t){const e=t[b];"function"==typeof e?e.call(t,o).catch(e=>{j(`Error in ${b}: ${e instanceof Error?e.message:String(e)}`)}):j(`${b} is not a function.`)}}function pi(e){const t=new Set,n=new Set,o=function(e){let t={},n=e;for(;n&&n!==Object.prototype;)Object.assign(t,Object.getOwnPropertyDescriptors(n)),n=Object.getPrototypeOf(n);return t}(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterPaths:t,setterPaths:n}}class hi extends ps{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return Ts(e)}__state;_hasUpdatedCallback=!1;_crossRowListPaths=new Set;_name="default";_initialized=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new Vs}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_dcc=!1;_connectGeneration=0;_streamsStartedGeneration=0;constructor(){super(),this._initializePromise=new Promise(e=>{this._resolveInitialize=e}),this._connectedCallbackPromise=new Promise(e=>{this._resolveConnectedCallback=e}),this._loadingPromise=new Promise(e=>{this._resolveLoading=e}),this._setStatePromise=new Promise(e=>{this._resolveSetState=e})}get _state(){return void 0===this.__state&&j(`${n.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){this._commandTokenNames=function(e){const t=new Set,n=e[w];if(void 0===n)return t;Array.isArray(n)||j(`${w} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||j(`${w} entries must be non-empty strings.`),e===N&&j(`${w} entry "${e}" conflicts with the reserved namespace name "${N}".`),t.has(e)&&j(`${w} entry "${e}" is duplicated.`),t.add(e);return t}(t),this._eventTokenNames=function(e){const t=new Set,n=e[v];if(void 0===n)return t;Array.isArray(n)||j(`${v} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||j(`${v} entries must be non-empty strings.`),t.has(e)&&j(`${v} entry "${e}" is duplicated.`),t.add(e);return t}(t),this.__state=t,this._hasUpdatedCallback=g in t,St(this),function(e,t,n){const o=t[S];if(void 0!==o){"object"==typeof o&&null!==o||j(`${S} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||j(`${S} entry "${t}" is not declared in $eventTokens.`),"function"!=typeof s&&j(`${S} entry "${t}" must be a function.`),vt(e,t).subscribe(s)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const n=pi(t);for(const e of n.getterPaths)this._getterPaths.add(e);for(const e of n.setterPaths)this._setterPaths.add(e);var o;hr(this),rr(o=this),tr(o),or.delete(o),cr(this,t),this._initialized&&null!==this._rootNode&&!e()&&(br(this),this._streamsStartedGeneration=this._connectGeneration),this._resolveLoading?.()}get name(){return this._name}_loadFromSsrElement(){if(!this.hasAttribute("enable-ssr"))return null;const e=this.getAttribute("name")||"default",t=this.parentNode;if(!t)return null;const n=ws.findByName(t,e);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 e=this.getAttribute("state");this._state=function(e){const t=document.getElementById(e);if(t&&"application/json"===t.type)try{return JSON.parse(t.textContent||"{}")}catch(e){j("Failed to parse JSON from script element:"+e)}return{}}(e)}else if(this.hasAttribute("src")){const e=this.getAttribute("src");e&&e.endsWith(".json")?this._state=await async function(e){try{const t=await fetch(e);return t.ok||j(`Failed to fetch JSON file: ${t.statusText}`),await t.json()}catch(e){return console.error("Failed to load JSON file:",e),{}}}(e):e&&e.endsWith(".js")?this._state=await Us(e):j(`Unsupported src file type: ${e}`)}else if(this.hasAttribute("json")){const e=this.getAttribute("json");this._state=JSON.parse(e)}else{const e=this.querySelector('script[type="module"]');if(e)this._state=await qs(e,`${this._name}`);else{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${n.tagNames.state}> element with name="${this._name}".`)},6e4);this._state=await this._setStatePromise,clearTimeout(e)}}}catch(e){j(`Failed to initialize state: ${e}`)}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",ks(this.rootNode,this._name,this)}async _initializeBindWebComponent(){if(this.hasAttribute("bind-component")){const e=this.parentNode,t=e instanceof ShadowRoot?e.host:e instanceof Element?e:null,o=t?E(t):null;null!==t&&null!==o||j(`"bind-component" requires <${n.tagNames.state}> to be a direct child of a custom element.`),e instanceof ShadowRoot||this.hasAttribute("name")||j('"bind-component" in Light DOM requires a "name" attribute to avoid namespace conflicts with the parent scope.');const s=this.getAttribute("bind-component");await customElements.whenDefined(o.toLowerCase()),t.hasAttribute(n.bindAttributeName)&&await a(t),s in t||j(`Component does not have property "${s}" for state binding.`);const r=t[s];"object"==typeof r&&null!==r||j(`Component property "${s}" is not an object for state binding.`),this._boundComponent=t,this._boundComponentStateProp=s,fi(this,this._boundComponent,this._boundComponentStateProp,r)}}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{h in e&&await e[Oe]()})}async _initializeDCC(e,t){let o;try{if(this.hasAttribute("src")){const e=this.getAttribute("src");e.endsWith(".js")?o=await Us(e):j(`DCC: Unsupported src type: ${e}`)}else{const t=this.querySelector('script[type="module"]');t?o=await qs(t,e.tagName.toLowerCase()):j(`DCC: No state source found for "${e.tagName.toLowerCase()}".`)}}catch(e){j(`DCC: Failed to load state: ${e}`)}!function(e,t,o){const s=e.tagName.toLowerCase();if(s.includes("-")||j(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`),customElements.get(s))return void console.warn(`[@wcstack/state] DCC: "${s}" is already registered. Skipping redefinition.`);const r=document.createElement("template");r.innerHTML=t.innerHTML;const i=t.mode,a=Array.isArray(o[y])?o[y]:[],c=a.length>0?function(e,t){return{protocol:"wc-bindable",version:1,properties:t.map(t=>({name:t,event:`${e}:${t}-changed`})),inputs:t.map(e=>({name:e}))}}(s,a):null,l=a.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(s,a):{},d=`${n.tagNames.state}:not([name])`,u=class extends HTMLElement{static template=r;static shadowRootMode=i;static wcBindable=c;static bindableEventMap=l;_shadow=null;connectedCallback(){if(!this.hasAttribute(_)&&(this._shadow=this.attachShadow({mode:u.shadowRootMode}),this._shadow.appendChild(u.template.content.cloneNode(!0)),Object.keys(u.bindableEventMap).length>0)){const e=this._shadow.querySelector(d);e&&e.initializePromise.then(()=>{e.setBindableEventMap(u.bindableEventMap)})}}get stateElement(){return this._shadow?.querySelector(d)}},f=Object.getOwnPropertyDescriptors(o);for(const[e,t]of Object.entries(f)){if(xr(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=Sr(e,o)}else n.get=Nr(e),n.set=vr(e);Object.defineProperty(u.prototype,e,n)}customElements.define(s,u)}(e,t,o),this._dcc=!0,this._initialized=!0,this._rootNode=null,this._resolveInitialize?.(),this._resolveConnectedCallback?.()}_callStateDisconnectedCallback(){this.createState("writable",e=>{m in e&&e[De]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initialized)this._dcc||$s(this._rootNode,this._name)===this||ks(this._rootNode,this._name,this);else{const e=this.parentNode;if(e instanceof ShadowRoot&&e.host.hasAttribute(_))return void await this._initializeDCC(e.host,e);await this._initializeBindWebComponent(),await this._initialize(),this._initialized=!0,this._resolveInitialize?.()}if(this.hasAttribute("enable-ssr")&&!e()||await this._callStateConnectedCallback(),e()&&this.hasAttribute("enable-ssr")){await Ts(this.rootNode);const e=this.getAttribute("name")||"default",t=ws.extractStateData(this),o=document.createElement(n.tagNames.ssr);o.setAttribute("name",e),o.setAttribute("version",fs),ws.buildContent(o,t),this.parentNode?.insertBefore(o,this)}e()||null===this._rootNode||t!==this._connectGeneration||this._streamsStartedGeneration===t||br(this),this._resolveConnectedCallback?.()}disconnectedCallback(){if(null!==this._rootNode)try{this._callStateDisconnectedCallback()}finally{ks(this.rootNode,this._name,null),e=this,Hs.delete(e),function(e){Js.delete(e)}(this),St(this),rr(this),hr(this),this._rootNode=null}var e}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}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&&j("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(e){this._bindableEventMap=e}_addDependency(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(e,t){return this._addDependency(this._dynamicDependency,e,t)}addStaticDependency(e,t){return this._addDependency(this._staticDependency,e,t)}setPathInfo(e,t){if("for"===t&&(this._listPaths.add(e),this._elementPaths.add(e+"."+l)),!this._pathSet.has(e)){const t=T(e);if(this._pathSet.add(e),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=T(e.parentPath)}}}_createState(e,t,n){try{const o=function(e,t,n,o){const s=new Xr(e,n,o);return new Proxy(t,s)}(e,this._state,this._name,t);return n(o)}finally{}}async createStateAsync(e,t){return await this._createState(this.rootNode,e,t)}createState(e,t){this._createState(this.rootNode,e,t)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(e){this._crossRowListPaths.add(e)}bindProperty(e,t){Object.defineProperty(this._state,e,t),e===g&&(this._hasUpdatedCallback=!0)}setInitialState(e){this._initialized?this._state=e:this._resolveSetState?.(e)}}function mi(){customElements.get(n.tagNames.ssr)||customElements.define(n.tagNames.ssr,ws),customElements.get(n.tagNames.state)||customElements.define(n.tagNames.state,hi)}function gi(e){var n;e&&((n=e).tagNames&&Object.assign(t.tagNames,n.tagNames),"string"==typeof n.bindAttributeName&&(t.bindAttributeName=n.bindAttributeName),"string"==typeof n.commentTextPrefix&&(t.commentTextPrefix=n.commentTextPrefix),"string"==typeof n.commentForPrefix&&(t.commentForPrefix=n.commentForPrefix),"string"==typeof n.commentIfPrefix&&(t.commentIfPrefix=n.commentIfPrefix),"string"==typeof n.commentElseIfPrefix&&(t.commentElseIfPrefix=n.commentElseIfPrefix),"string"==typeof n.commentElsePrefix&&(t.commentElsePrefix=n.commentElsePrefix),"string"==typeof n.locale&&(t.locale=n.locale),"boolean"==typeof n.debug&&(t.debug=n.debug),"boolean"==typeof n.enableMustache&&(t.enableMustache=n.enableMustache),"boolean"==typeof n.enableDirectionalInitialSync&&(t.enableDirectionalInitialSync=n.enableDirectionalInitialSync),"boolean"==typeof n.enablePropagationContext&&(t.enablePropagationContext=n.enablePropagationContext),"boolean"==typeof n.enableContractAnalyzer&&(t.enableContractAnalyzer=n.enableContractAnalyzer),"boolean"==typeof n.sameValueGuard&&(t.sameValueGuard=n.sameValueGuard)),mi(),zs()}function bi(e){return e}const yi={eq:{description:"等しいか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},ne:{description:"異なるか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},not:{description:"ブール値を反転",hasArgs:!1,resultType:"boolean",acceptTypes:["boolean"],minArgs:0,maxArgs:0},lt:{description:"より小さいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},le:{description:"以下か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},gt:{description:"より大きいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},ge:{description:"以上か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},inc:{description:"加算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},dec:{description:"減算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},mul:{description:"乗算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},div:{description:"除算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mod:{description:"剰余",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},fix:{description:"固定小数点表記",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},locale:{description:"ロケール形式で数値フォーマット",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["string"]},uc:{description:"大文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},lc:{description:"小文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},cap:{description:"先頭文字を大文字に",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},trim:{description:"前後の空白を削除",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},slice:{description:"部分文字列 (start[,end])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},substr:{description:"部分文字列 (pos,len)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},pad:{description:"パディング (length[,char])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},rep:{description:"繰り返し (count)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:1,argTypes:["number"]},rev:{description:"文字順を反転",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},int:{description:"整数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},float:{description:"浮動小数点数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},round:{description:"四捨五入",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},floor:{description:"切り下げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},ceil:{description:"切り上げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},percent:{description:"パーセンテージ形式",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},date:{description:"ロケール形式の日付",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},time:{description:"ロケール形式の時刻",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},datetime:{description:"ロケール形式の日時",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},ymd:{description:"YYYY-MM-DD 形式",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},falsy:{description:"偽値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},truthy:{description:"真値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},defaults:{description:"偽値の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},boolean:{description:"ブール値に変換",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},number:{description:"数値に変換",hasArgs:!1,resultType:"number",acceptTypes:"any",minArgs:0,maxArgs:0},string:{description:"文字列に変換",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},null:{description:"空文字列をnullに変換",hasArgs:!1,resultType:"passthrough",acceptTypes:["string"],minArgs:0,maxArgs:0}},wi=1;function Ni(){return{version:1,syntax:{bindAttribute:n.bindAttributeName,tagName:n.tagNames.state,pathDelimiter:c,wildcard:l,delimiters:{binding:";",propValue:":",modifier:"#",stateName:"@",filter:u},structuralDirectives:Array.from(G)},filters:Object.keys(ee),filterMeta:yi,reservedLifecycle:[h,m,g,b],reservedStateApi:[y,w,N,v,S,x,I,A]}}const vi=new Set(["wcstack.types","wcstack.async","wcstack.platformCapabilities","wcstack.application"]),Si=Object.freeze([]);function xi(e){if(!n.enableContractAnalyzer)return Si;const t=[];return function(e,t,n){const o=e.manifestExtensions;if(null===o||"object"!=typeof o)return;for(const e of Object.keys(o))vi.has(e)||n({type:"contract:unsupported-extension",namespace:e});const s=o["wcstack.types"]?.components;if(null==s)return;for(const[e,o]of Object.entries(s)){const s=t(e);n({type:"contract:manifest-read",tag:e,loaded:null!==s}),null!==s?Ii(e,o,s,n):n({type:"contract:drift",reason:"component-not-loaded",tag:e})}}(e,Ai,e=>{t.push(e),null!==et&&et(e)}),t}function Ii(e,t,n,o){const s=null!==t&&"object"==typeof t?t:{};for(const[t,r]of Object.entries(s.observables??{})){if(!n.propertyEvents.has(t)){o({type:"contract:drift",reason:"missing-member",tag:e,member:t});continue}const s=n.propertyEvents.get(t),i=r?.event;"string"==typeof i&&i!==s&&o({type:"contract:drift",reason:"event-mismatch",tag:e,member:t,sidecarEvent:i,liveEvent:s})}for(const t of Object.keys(s.inputs??{}))n.inputs.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t});for(const t of Object.keys(s.commands??{}))n.commands.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t})}function Ai(e){const t=M(),n=t?.get(e);if(void 0===n)return null;const o=n.wcBindable;if(null===o||"object"!=typeof o||"wc-bindable"!==o.protocol)return null;const s=o,r=new Map;for(const e of Array.isArray(s.properties)?s.properties:[])"string"==typeof e?.name&&"string"==typeof e.event&&r.set(e.name,e.event);const i=new Set;for(const e of Array.isArray(s.inputs)?s.inputs:[])"string"==typeof e?.name&&i.add(e.name);const a=new Set;for(const e of Array.isArray(s.commands)?s.commands:[])"string"==typeof e?.name&&a.add(e.name);return{propertyEvents:r,inputs:i,commands:a}}export{ws as Ssr,fs as VERSION,wi as WCS_MANIFEST_VERSION,xi as analyzeContract,gi as bootstrapState,us as buildBindings,yi as builtinFilterMeta,bi as defineState,Ts as getBindingsReady,o as getConfig,Ni as getWcsManifest};
1
+ function e(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const t={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=t;function o(){return n}const s=new WeakMap;let r=0;function i(e){let t,n=s.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++r,promise:o,resolve:t},s.set(e,n),n}async function a(e){const t=i(e);await t.promise}const c=".",l="*",d=128,u="|",f={};for(let e=0;e<128;e++)f[`$${e+1}`]=e;const p=Object.freeze(f),h="$connectedCallback",m="$disconnectedCallback",g="$updatedCallback",b="$stateReadyCallback",y="$bindables",w="$commandTokens",N="$command",v="$eventTokens",S="$on",x="$streams",I="$streamStatus",A="$streamError",_="data-wc-definition",P=new Map;let $=0;function T(e){let t=P.get(e);return void 0!==t||(t=Object.freeze(new k(e)),P.set(e,t)),t}class k{id=++$;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(e){const t=t=>e===t?this:T(t),n=e.split("."),o=[],s=[],r=[],i={},a=[],c=[],d=[],u=[];let f="",p="",h=0;for(let e=0;e<n.length;e++)f+=n[e],n[e]===l&&(r.push(f),i[f]=h,a.push(t(f)),c.push(p),d.push(t(p)),u.push(e),h++),o.push(f),s.push(t(f)),p=f,f+=".";const m=r.length>0?r[r.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=e,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=r,this.wildcardPathSet=new Set(r),this.indexByWildcardPath=i,this.wildcardPathInfos=a,this.wildcardPathInfoSet=new Set(a),this.wildcardParentPaths=c,this.wildcardParentPathSet=new Set(c),this.wildcardParentPathInfos=d,this.wildcardParentPathInfoSet=new Set(d),this.wildcardPositions=u,this.lastWildcardPath=m,this.lastWildcardInfo=m?t(m):null,this.parentPath=g,this.parentPathInfo=g?t(g):null,this.wildcardCount=h}}const C=new WeakMap;function E(e){const t=C.get(e);if(void 0!==t)return t;let n=null;try{if(e.nodeType!==Node.ELEMENT_NODE)return n;const t=e,o=t.tagName.toLowerCase();if(o.includes("-"))return n=o;if(t.hasAttribute("is")){const e=t.getAttribute("is");if(e.includes("-"))return n=e}return n}finally{C.set(e,n)}}function M(e=null){const t=globalThis.customElements,n=e?.customElements??t;if("object"!=typeof n||null===n)return null;const o=n;return"function"!=typeof o.get||"function"!=typeof o.whenDefined?null:o}function O(e,t){e.upgrade?.(t)}function D(e){try{if(null===e||"object"!=typeof e&&"function"!=typeof e)return null;const t=e,n=t.addEventListener,o=t.removeEventListener,s=t.constructor?.wcBindable;if("function"!=typeof n||"function"!=typeof o)return null;if("wc-bindable"!==s?.protocol)return null;if(!Number.isInteger(s.version)||s.version<1)return null;const r=B(s.properties,R);if(null===r)return null;const i=void 0===s.inputs?new Map:B(s.inputs,L);if(null===i)return null;const a=void 0===s.commands?new Map:B(s.commands,W);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function R(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&("string"==typeof t.event&&0!==t.event.length&&(void 0===t.getter||"function"==typeof t.getter))}function L(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.attribute||"string"==typeof t.attribute)}function W(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.async||"boolean"==typeof t.async)}function B(e,t){if(!Array.isArray(e))return null;const n=new Map;for(const o of e){if(!t(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function j(e){throw new Error(`[@wcstack/state] ${e}`)}function F(e,t,n){const o="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:o,statePathInfo:T(o),stateName:n,inFilters:[],outFilters:[],bindingType:"prop"}}function z(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function q(e,t){let n=e;if(0===t.length)return n;for(let e=0;e<t.length&&(n=n?.childNodes[t[e]]??null,null!==n);e++);return n}const U=new WeakMap;function V(e){return U.get(e)||null}function H(e,t){U.set(e,t)}const G=new Set(["if","elseif","else","for"]);function J(e){j(`filter ${e} requires at least one option`)}function K(e){j(`filter ${e} requires a number as option`)}function Y(e){j(`filter ${e} requires a number value`)}function X(e){j(`filter ${e} requires a date value`)}function Q(e){return!(!e||isNaN(Number(e)))}const Z={eq:e=>{const t=e?.[0]??J("eq");return e=>"number"==typeof e?(Q(t)||K("eq"),e===Number(t)):e===t},ne:e=>{const t=e?.[0]??J("ne");return e=>"number"==typeof e?(Q(t)||K("ne"),e!==Number(t)):e!==t},not:e=>e=>("boolean"!=typeof e&&j(`filter ${"not"} requires a boolean value`),!e),lt:e=>{const t=e?.[0]??J("lt");return Q(t)||K("lt"),e=>("number"!=typeof e&&Y("lt"),e<Number(t))},le:e=>{const t=e?.[0]??J("le");return Q(t)||K("le"),e=>("number"!=typeof e&&Y("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??J("gt");return Q(t)||K("gt"),e=>("number"!=typeof e&&Y("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??J("ge");return Q(t)||K("ge"),e=>("number"!=typeof e&&Y("ge"),e>=Number(t))},inc:e=>{const t=e?.[0]??J("inc");return Q(t)||K("inc"),e=>("number"!=typeof e&&Y("inc"),e+Number(t))},dec:e=>{const t=e?.[0]??J("dec");return Q(t)||K("dec"),e=>("number"!=typeof e&&Y("dec"),e-Number(t))},mul:e=>{const t=e?.[0]??J("mul");return Q(t)||K("mul"),e=>("number"!=typeof e&&Y("mul"),e*Number(t))},div:e=>{const t=e?.[0]??J("div");return Q(t)||K("div"),e=>("number"!=typeof e&&Y("div"),e/Number(t))},mod:e=>{const t=e?.[0]??J("mod");return Q(t)||K("mod"),e=>("number"!=typeof e&&Y("mod"),e%Number(t))},fix:e=>{const t=e?.[0]??"0";return Q(t)||K("fix"),e=>("number"!=typeof e&&Y("fix"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0]??n.locale;return e=>("number"!=typeof e&&Y("locale"),e.toLocaleString(t))},uc:e=>e=>String(e).toUpperCase(),lc:e=>e=>String(e).toLowerCase(),cap:e=>e=>{const t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)},trim:e=>e=>String(e).trim(),slice:e=>{const t=[],n=e?.[0]??J("slice");Q(n)||K("slice"),t.push(Number(n));const o=e?.[1];return void 0!==o&&(Q(o)||K("slice"),t.push(Number(o))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??J("substr");Q(t)||K("substr");const n=e?.[1]??J("substr");return Q(n)||K("substr"),e=>String(e).substr(Number(t),Number(n))},pad:e=>{const t=e?.[0]??J("pad");Q(t)||K("pad");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},rep:e=>{const t=e?.[0]??J("rep");return Q(t)||K("rep"),e=>String(e).repeat(Number(t))},rev:e=>e=>String(e).split("").reverse().join(""),int:e=>e=>parseInt(String(e),10),float:e=>e=>parseFloat(String(e)),round:e=>{const t=e?.[0]??"0";return Q(t)||K("round"),e=>{"number"!=typeof e&&Y("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return Q(t)||K("floor"),e=>{"number"!=typeof e&&Y("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return Q(t)||K("ceil"),e=>{"number"!=typeof e&&Y("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return Q(t)||K("percent"),e=>("number"!=typeof e&&Y("percent"),`${(100*e).toFixed(Number(t))}%`)},date:e=>{const t=e?.[0]??n.locale;return e=>(e instanceof Date||X("date"),e.toLocaleDateString(t))},time:e=>{const t=e?.[0]??n.locale;return e=>(e instanceof Date||X("time"),e.toLocaleTimeString(t))},datetime:e=>{const t=e?.[0]??n.locale;return e=>(e instanceof Date||X("datetime"),e.toLocaleString(t))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||X("ymd");const n=e.getFullYear().toString(),o=(e.getMonth()+1).toString().padStart(2,"0"),s=e.getDate().toString().padStart(2,"0");return`${n}${t}${o}${t}${s}`}},falsy:e=>e=>!1===e||null==e||0===e||""===e||Number.isNaN(e),truthy:e=>e=>!1!==e&&null!=e&&0!==e&&""!==e&&!Number.isNaN(e),defaults:e=>{const t=e?.[0]??J("defaults");return e=>!1===e||null==e||0===e||""===e||Number.isNaN(e)?t:e},boolean:e=>e=>Boolean(e),number:e=>e=>Number(e),string:e=>e=>String(e),null:e=>e=>""===e?null:e},ee=Z,te={input:Z,output:ee},ne=(e,t)=>n=>{const o=n[e];return o||j(`filter not found: ${e}`),o(t)};const oe=new Map;function se(e,t){const n=te[t];return e.map(e=>{const o=e.indexOf("("),s=e.lastIndexOf(")");if(-1!==o&&-1===s&&j(`Invalid filter format: missing closing parenthesis in "${e}"`),-1!==s&&-1===o&&j(`Invalid filter format: missing opening parenthesis in "${e}"`),-1===o){const o=e.trim(),s=`${o}():${t}`;let r=oe.get(s);return void 0===r&&(r=ne(o,[])(n),oe.set(s,r)),{filterName:o,args:[],filterFn:r}}{const r=e.substring(o+1,s),i=e.substring(0,o).trim(),a=function(e){const t=[];let n="",o=null,s=!1;for(let r=0;r<e.length;r++){const i=e[r];o?i===o?o=null:n+=i:'"'===i||"'"===i?(o=i,s=!0):","===i?(t.push(n.trim()),n="",s=!1):n+=i}const r=n.trim();return(r||s)&&t.push(r),t}(r),c=`${i}(${a.join(",")}):${t}`;let l=oe.get(c);return void 0===l&&(l=ne(i,a)(n),oe.set(c,l)),{filterName:i,args:a,filterFn:l}}})}const re=e=>e.trim(),ie=new Map;const ae=new Map;function ce(e){const t=e.indexOf(u);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),ae.has(s)?r=ae.get(s):(o=s.split(u).map(re),r=se(o,"output"),ae.set(s,r))):n=e.trim();const[i,a="default"]=n.split("@").map(re);return{stateName:a,statePathName:i,statePathInfo:T(i),outFilters:r}}function le(e){const[...t]=e.split(";").map(re).filter(e=>e.length>0),n=t.map(e=>{const t=e.indexOf(":");-1===t&&j(`Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.`);const n=e.slice(0,t).trim(),o=e.slice(t+1).trim();if("else"===n){return{propName:"else",propSegments:["else"],propModifiers:[],statePathName:"#else",statePathInfo:T("#else"),stateName:"",inFilters:[],outFilters:[],bindingType:"else"}}if("..."===n){const t=ce(o);return t.outFilters.length>0&&j(`Invalid spread binding "${e}": filters are not allowed on spread targets.`),0===t.statePathName.length&&j(`Invalid spread binding "${e}": spread target path is required.`),{propName:"...",propSegments:["..."],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n||"radio"===n||"checkbox"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...ce(o),bindingType:n}}{const e=ce(o),t=function(e){const t=e.indexOf(u);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),ie.has(s)?r=ie.get(s):(o=s.split(u).map(re),r=se(o,"input"),ie.set(s,r))):n=e.trim();const[i,a]=n.split("#").map(re),l=i.split(c).map(re);return{propName:i,propSegments:l,propModifiers:a?a.split(",").map(re):[],inFilters:r}}(n);return"eventToken"===t.propSegments[0]||t.propSegments[0].startsWith("on")?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>G.has(e.bindingType))&&j(`Invalid bindText: "${e}". 'if', 'elseif', 'else', and 'for' bindings must be single binding.`)}return n}const de=new WeakMap,ue=new Set([n.commentTextPrefix,n.commentForPrefix,n.commentIfPrefix,n.commentElseIfPrefix,n.commentElsePrefix]),fe=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function pe(e){const t=de.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const o=e.data.trim(),s=fe.exec(o);if(null===s)return null;const r=s[1]||n.commentTextPrefix;return ue.has(r)?(de.set(e,s[2]),s[2]):null}const he=new Map;function me(e,t,n){if(null===n)he.delete(e);else{he.set(e,n);const o=n.parseBindTextResult,s=$s(t,o.stateName);null===s&&j(`State element with name "${o.stateName}" not found for fragment info.`),s.setPathInfo(o.statePathName,o.bindingType);for(const e of n.nodeInfos)for(const n of e.parseBindTextResults){const e=$s(t,n.stateName);null===e&&j(`State element with name "${n.stateName}" not found for fragment info node.`),e.setPathInfo(n.statePathName,n.bindingType)}}}function ge(e){return he.get(e)||null}function be(e){if(e.nodeType===Node.ELEMENT_NODE){return le(e.getAttribute(n.bindAttributeName)||"")}if(e.nodeType===Node.COMMENT_NODE){const t=pe(e);null===t&&j("Comment node binding text not found.");const n=ge(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o={propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...ce(t),bindingType:"text"},s=null):s=t,[{...o,uuid:s}]}return[]}function ye(e){const t=[],o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(e){if(e.nodeType===Node.ELEMENT_NODE){return e.hasAttribute(n.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==pe(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;o.nextNode();)t.push(o.currentNode);return t}const we=new WeakSet;function Ne(e,t,o){const s=function(e,t,o={}){const s=o.allowDeferred??!0;if(!t.some(e=>"spread"===e.bindingType))return t;const r=[],i=new WeakSet;for(const n of t){if("spread"!==n.bindingType){r.push(n);continue}e.nodeType!==Node.ELEMENT_NODE&&j("Spread binding requires an element node.");const t=e,o=E(t);null===o&&j(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=M();if(null===a&&j(`CustomElementRegistry is unavailable for <${o}>.`),void 0===a.get(o)){s||j(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}O(a,t);const c=D(t);null===c&&j(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const l=n.statePathName,d=n.stateName,u=new Set;for(const e of c.knownProperties.keys()){if(u.has(e))continue;u.add(e);const t=F(e,l,d);i.add(t),r.push(t)}for(const e of c.declaredInputs.keys()){if(u.has(e))continue;u.add(e);const t=F(e,l,d);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=z(r[e]);null!==t&&a.set(t,e)}const c=[];for(let t=0;t<r.length;t++){const o=z(r[t]);if(null!==o){if(a.get(o)===t)c.push(r[t]);else if(n.debug&&i.has(r[t])){const n=r[a.get(o)],s=e.nodeType===Node.ELEMENT_NODE?`<${e.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[t].propName}" of ${s} overridden by explicit binding (statePath: "${n.statePathName}").`)}}else c.push(r[t])}return c}(e,t,{allowDeferred:o.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?E(e):null;return null===n&&j("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t}}}we.add(e);const r=function(e,t){const n=[];for(const o of t)if("text"!==o.bindingType)n.push({...o,node:e,replaceNode:e});else{const t=document.createTextNode("");n.push({...o,node:e,replaceNode:t})}return n}(e,s);return H(e,r),function(e){i(e).resolve()}(e),{bindings:r,deferred:null}}function ve(e){const t=ye(e),n=[],o=[];for(const e of t){if(we.has(e))continue;const t=Ne(e,be(e),{allowDeferred:!0});null===t.deferred?n.push(...t.bindings):o.push(t.deferred)}return[t,n,o]}function Se(e){const{node:t,parseResults:n}=e;!function(e){we.delete(e)}(t);return Ne(t,n,{allowDeferred:!1}).bindings}const xe=new WeakMap;function Ie(e){let t=e;for(;t;){const e=xe.get(t);if(e)return e;t=t.parentNode}return null}function Ae(e,t){null!==t?xe.set(e,t):xe.delete(e)}const _e=new WeakMap;function Pe(e){return _e.get(e)??[]}function $e(e,t){_e.set(e,t)}const Te=Symbol("$$setLoopContextAsync"),ke=Symbol("$$setLoopContext"),Ce=Symbol("$$getByAddress"),Ee=Symbol("$$hasByAddress"),Me=Symbol("$$setByAddress"),Oe=Symbol("$$connectedCallback"),De=Symbol("$$disconnectedCallback"),Re=Symbol("$$updatedCallback"),Le=new WeakMap;function We(e,t){if(Le.has(e)){const n=Le.get(e);if(n.has(t))return n.get(t)}else Le.set(e,new WeakMap);const n=Object.freeze(new Be(e,t));return Le.get(e).set(t,n),n}class Be{pathInfo;stateName;stateElement;parentAbsolutePathInfo;constructor(e,t){this.pathInfo=t,this.stateName=e.name,this.stateElement=e,null===t.parentPathInfo?this.parentAbsolutePathInfo=null:this.parentAbsolutePathInfo=We(e,t.parentPathInfo)}}const je=new WeakMap,Fe=new WeakMap;class ze{absolutePathInfo;listIndex;_parentAbsoluteAddress;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}get parentAbsoluteAddress(){if(void 0!==this._parentAbsoluteAddress)return this._parentAbsoluteAddress;const e=this.absolutePathInfo.parentAbsolutePathInfo;if(null===e)return null;let t=null;return t=this.absolutePathInfo.pathInfo.segments[this.absolutePathInfo.pathInfo.segments.length-1]===l?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAbsoluteAddress=qe(e,t)}}function qe(e,t){if(null===t){let t=Fe.get(e);return void 0!==t||(t=new ze(e,null),Fe.set(e,t)),t}{let n=je.get(t);void 0===n&&(n=new WeakMap,je.set(t,n));let o=n.get(e);return void 0!==o||(o=new ze(e,t),n.set(e,o)),o}}const Ue=new WeakMap;function Ve(e,t){null===t?Ue.delete(e):Ue.set(e,t)}function He(e){return Ue.get(e)||null}const Ge=new Map;function Je(e,t){let n,o;if(0===e.wildcardCount||0===t.wildcardCount)return 0;if(1===e.wildcardCount&&t.wildcardCount>0&&t.wildcardPathSet.has(e.path))return 1;e.id<t.id?(n=e,o=t):(n=t,o=e);const s=`${n.path}\t${o.path}`;let r=Ge.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,Ge.set(s,r),r}const Ke=new WeakMap;function Ye(e){const t=Ie(e.node);if(null===t)return null;let n=Ke.get(t);if(void 0===n)n=new WeakMap,Ke.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=Je(t.pathInfo,e.statePathInfo);return n>0&&(o=t.listIndex.at(n-1)),o}finally{n.set(e,o)}}const Xe=new WeakMap;function Qe(e){let t=null;if(t=Xe.get(e)||null,null!==t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=He(n);null===t?j(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}const o=Ye(e),s=$s(n,e.stateName);null===s&&j(`State element with name "${e.stateName}" not found for binding.`);return t=qe(We(s,e.statePathInfo),o),Xe.set(e,t),t}function Ze(e){Xe.delete(e)}let et=null;const tt=new WeakMap;function nt(e){return tt.get(e)}function ot(e,t){const n=function(e){let t=null;return t=tt.get(e)||null,null===t&&(t=new Set,tt.set(e,t)),t}(e);n.add(t),null!==et&&et({type:"state:binding-added",absoluteAddress:e,binding:t})}function st(e,t){const n=tt.get(e);void 0!==n&&(n.delete(t),null!==et&&et({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const rt=new WeakMap,it=new WeakMap;class at{pathInfo;listIndex;_parentAddress;constructor(e,t){this.pathInfo=e,this.listIndex=t}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const e=this.pathInfo.parentPathInfo;if(null===e)return null;let t=null;return t=this.pathInfo.segments[this.pathInfo.segments.length-1]===l?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=ct(e,t)}}function ct(e,t){if(null===t){let t=it.get(e);return void 0!==t||(t=new at(e,null),it.set(e,t)),t}{let n=rt.get(t);void 0===n&&(n=new WeakMap,rt.set(t,n));let o=n.get(e);return void 0!==o||(o=new at(e,t),n.set(e,o)),o}}const lt=new WeakMap;function dt(e){let t=null;if(t=lt.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=Ye(e);null===n&&j(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=ct(e.statePathInfo,n)}else t=ct(e.statePathInfo,null);return lt.set(e,t),t}function ut(e){lt.delete(e)}function ft(){const e=new Map,t=new Map;return{add(n,o){let s=e.get(n);return void 0===s&&(s=new WeakSet,e.set(n,s)),!s.has(o)&&(s.add(o),t.set(n,(t.get(n)??0)+1),!0)},remove(n,o){const s=e.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(t.get(n)??1)-1;return r<=0?(e.delete(n),t.delete(n),!0):(t.set(n,r),!1)},has:(t,n)=>e.get(t)?.has(n)??!1,countOf:e=>t.get(e)??0,get keyCount(){return t.size},clear(){e.clear(),t.clear()}}}const pt=new Map,ht=ft();function mt(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.stateName}::${e.statePathName}::${t}::${n}`}function gt(e){let t="input";for(const n of e.propModifiers)n.startsWith("on")&&(t=n.slice(2));return t}function bt(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf("ro")){const s=gt(e),r=mt(e,s);let i=pt.get(r);return void 0===i&&(t=e.stateName,n=e.statePathName,o=e.inFilters,i=e=>{const s=e.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 e of o)i=e.filterFn(i);const a=$s(s.getRootNode(),t);null===a&&j(`State element with name "${t}" not found for two-way binding.`);const c=Ie(s);a.createState("writable",e=>{e[ke](c,()=>{let t=e[n];if(Array.isArray(t))if(r)-1===t.indexOf(i)&&(e[n]=t.concat(i));else{const o=t.indexOf(i);-1!==o&&(e[n]=t.toSpliced(o,1))}else e[n]=r?[i]:[]})})},pt.set(r,i)),e.node.addEventListener(s,i),ht.add(r,e),!0}var t,n,o;return!1}class yt{_name;_subscribers=new Set;constructor(e){this._name=e}get name(){return this._name}get size(){return this._subscribers.size}subscribe(e){return this._subscribers.add(e),()=>{this._subscribers.delete(e)}}unsubscribe(e){return this._subscribers.delete(e)}emit(...e){const t=[];for(const n of this._subscribers)t.push(n(...e));return t}}class wt extends yt{_ownerStateName;constructor(e,t){super(e),this._ownerStateName=t??null}emit(...e){return null!==et&&et({type:"state:token-emit",kind:"event",stateName:this._ownerStateName,tokenName:this.name,args:e,subscriberCount:this.size}),super.emit(...e)}}const Nt=new WeakMap;function vt(e,t){let n=Nt.get(e);void 0===n&&(n=new Map,Nt.set(e,n));let o=n.get(t);return void 0===o&&(o=new wt(t,e.name),n.set(t,o)),o}function St(e){Nt.delete(e)}const xt=new WeakMap;function It(e){if("eventToken"!==e.propSegments[0])return!1;const t=e.node,n=E(t),o=M();if(null!==n&&void 0===o?.get(n))return null===o&&j(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(xt.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||j('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===E(e)?null:D(e)}(t);null===r&&j(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&j(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.`);const a=i.event,c=e.statePathName,l=e.stateName,d=e.propModifiers,u=e=>{d.includes("prevent")&&e.preventDefault(),d.includes("stop")&&e.stopPropagation();const n=$s(t.getRootNode(),l);null===n&&j(`State element with name "${l}" not found for eventToken handler.`),n.eventTokenNames.has(c)||j(`eventToken "${c}" is not declared in $eventTokens of state "${l}".`);const o=Ie(t);n.createStateAsync("writable",async t=>{t[ke](o,()=>{const s=o?.listIndex.indexes??[];return vt(n,c).emit(t,e,...s)})})};return t.addEventListener(a,u),xt.set(e,{eventName:a,handler:u}),!0}class At extends yt{_ownerStateName;constructor(e,t){super(e),this._ownerStateName=t??null}emit(...e){return null!==et&&et({type:"state:token-emit",kind:"command",stateName:this._ownerStateName,tokenName:this.name,args:e,subscriberCount:this.size}),super.emit(...e)}}function _t(e){return e instanceof At}const Pt=new Map,$t=ft();function Tt(e){const t=e.propModifiers.filter(e=>"prevent"===e||"stop"===e).sort().join(",");return`${e.stateName}::${e.statePathName}::${t}`}const kt=(e,t,n,o)=>s=>{n.includes("prevent")&&s.preventDefault(),n.includes("stop")&&s.stopPropagation();const r=s.target,i=$s(r.getRootNode(),e);null===i&&j(`State element with name "${e}" not found for event handler.`);const a=Ie(r),c=t.startsWith(N+".");i.createStateAsync("writable",async n=>{n[ke](a,()=>{const r=a?.listIndex.indexes??[];if(c){const e=n[Ce](ct(o,null));return _t(e)||j(`Event binding "${t}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),e.emit(s,...r)}const i=n[t];return"function"!=typeof i&&j(`Handler "${t}" is not a function on state "${e}".`),Reflect.apply(i,n,[s,...r])})})};const Ct=new Map,Et=ft();function Mt(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.stateName}::${e.statePathName}::${t}::${n}`}function Ot(e){let t="input";for(const n of e.propModifiers)n.startsWith("on")&&(t=n.slice(2));return t}function Dt(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf("ro")){const s=Ot(e),r=Mt(e,s);let i=Ct.get(r);return void 0===i&&(t=e.stateName,n=e.statePathName,o=e.inFilters,i=e=>{const s=e.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 e of o)r=e.filterFn(r);const i=$s(s.getRootNode(),t);null===i&&j(`State element with name "${t}" not found for two-way binding.`);const a=Ie(s);i.createState("writable",e=>{e[ke](a,()=>{e[n]=r})})},Ct.set(r,i)),e.node.addEventListener(s,i),Et.add(r,e),!0}var t,n,o;return!1}const Rt=new Set(["radio","checkbox"]),Lt=new Set(["value","valueAsNumber","valueAsDate"]);function Wt(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return!1;const n=e,o=n.tagName.toLowerCase();if("input"===o){const e=(n.getAttribute("type")||"text").toLowerCase();if("button"===e)return!1;if(Rt.has(e)&&"checked"===t)return!0;if(Lt.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=E(n);if(null!==s){const e=M()?.get(s);void 0===e&&j(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=D(n);if(o?.knownProperties.has(t))return!0}return!1}let Bt=1,jt=1,Ft=1;const zt=new WeakMap;function qt(e,t,n,o){let s=zt.get(e);void 0===s&&(s=new Map,zt.set(e,s));const r=function(e,t,n){return`${t}::${n}::${e}`}(t,n,o);let i=s.get(r);return void 0===i&&(i=Bt++,s.set(r,i)),i}function Ut(e,t){return"to-element"===t?2*e:2*e+1}const Vt=new Set;function Ht(e){return{transactionId:jt++,originBindingId:e,visitedEdges:Vt,hop:0}}function Gt(e,t){const n=new Set(e.visitedEdges);return n.add(t),{transactionId:e.transactionId,originBindingId:e.originBindingId,visitedEdges:n,hop:e.hop+1}}let Jt=null;function Kt(){return Jt}function Yt(e,t){const n=Jt;Jt=e;try{return t()}finally{Jt=n}}const Xt=[];const Qt=new Map,Zt=ft(),en=new WeakMap,tn=e=>e.detail;function nn(e,t,n){const o=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.stateName}::${e.propName}::${e.statePathName}::${t}::${o}::${n?"g":"n"}`}function on(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=E(e.node);if(null!==n){const o=M()?.get(n);void 0===o&&j(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=D(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith("on")&&(t=n.slice(2));return t}function sn(e){if(null!==E(e.node)){const t=D(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??tn}return null}const rn=(e,t,o,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let c;if(null!==r)c=r(i);else{if(!(t in a))return void console.warn(`[@wcstack/state] Property "${t}" does not exist on target element.`);c=a[t]}let l=c;for(const e of s)l=e.filterFn(l);const d=en.get(a)?.get(t);if(void 0!==d)for(const e of d)e(l);let u=null;if(n.enablePropagationContext){const s=qt(a,t,e,o),r=function(e,t){for(let n=Xt.length-1;n>=0;n--){const o=Xt[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,t);if(null!==r&&Object.is(r.writtenValue,c))return n.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:t,statePathName:o,transactionId:r.transactionId,coveredBySameValueGuard:n.sameValueGuard&&(null===l||"object"!=typeof l)}),void(null!==et&&et({type:"propagation:suppressed",reason:"confirmation",transactionId:r.transactionId,edgeId:Ut(s,"to-state"),node:a,member:t}));const i=Ut(s,"to-state"),d=Kt();if(null!==d&&d.visitedEdges.has(i))return void(null!==et&&et({type:"propagation:suppressed",reason:"visited-edge",transactionId:d.transactionId,edgeId:i,node:a,member:t}));u=Gt(d??Ht(s),i)}const f=$s(a.getRootNode(),e);null===f&&j(`State element with name "${e}" not found for two-way binding.`);const p=Ie(a),h=()=>{f.createState("writable",e=>{e[ke](p,()=>{e[o]=l})})};null!==u?Yt(u,h):h()};class an{registry;entries=new Map;constructor(e){this.registry=e}wait(e,t,n=()=>{}){const o=e.toLowerCase();let s=this.entries.get(o);void 0===s&&(s={waiters:new Set},this.entries.set(o,s),this.registry.whenDefined(o).then(()=>this.settle(o,null),e=>this.settle(o,e)));const r={active:!0,resolve:t,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(e){return this.entries.get(e.toLowerCase())?.waiters.size??0}settle(e,t){const n=this.entries.get(e);if(void 0===n)return;this.entries.delete(e);const o=Array.from(n.waiters);n.waiters.clear();for(const e of o)e.active&&(e.active=!1,null===t?e.resolve():e.reject(t))}}const cn=new WeakMap;function ln(e){let t=cn.get(e);return void 0===t&&(t=new an(e),cn.set(e,t)),t}function dn(e,t){let n=null;for(const o of e.propModifiers){const e=o.indexOf("=");if(e<0)continue;const s=o.slice(0,e).trim(),r=o.slice(e+1).trim();"init"!==s&&"sync"!==s&&j(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&j(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function un(e){return e.propModifiers.some(e=>e.includes("="))}function fn(e){if(!n.enableDirectionalInitialSync)return un(e)&&j("init=/sync= modifiers require enableDirectionalInitialSync."),{authority:"state",syncOn:"call",observable:!1};const t=null===(o=dn(e,"init"))?null:"state"===o||"element"===o||"auto"===o||"none"===o?o:j(`Invalid init modifier value "${o}".`);var o;const s=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":j(`Invalid sync modifier value "${e}".`)}(dn(e,"sync"));if("event"===e.bindingType)return null!==t&&"none"!==t&&j("Event bindings only allow init=none."),{authority:"none",syncOn:s,observable:!1};if("command"===e.propSegments[0])return{authority:"state",syncOn:s,observable:!1};if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&j(`Binding type "${e.bindingType}" does not support init=${t}.`),{authority:t??"state",syncOn:s,observable:!1};const r=D(e.node);if(null===r)return{authority:t??"state",syncOn:s,observable:!1};const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||j(`Property "${e.propName}" is not declared by wcBindable.`);const c=t??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(c)||j(`init=${c} is incompatible with wcBindable member "${e.propName}".`),"connect"!==s||i||j(`sync=connect requires observable property "${e.propName}".`),{authority:c,syncOn:s,observable:i}}function pn(e,t){return"auto"!==t?t:function(e){const t=$s(e.replaceNode.getRootNode(),e.stateName);null===t&&j(`State element with name "${e.stateName}" not found for binding.`);const n=dt(e);let o=!1;return t.createState("readonly",e=>{o=e[Ee](n)}),o}(e)?"state":"element"}let hn=0,mn=0;const gn=new WeakMap,bn=new WeakMap;function yn(e,t){t(e);for(const n of Array.from(e.childNodes))yn(n,t)}class wn{root;sessionRefs=new Set;knownSessions=new WeakSet;observer;constructor(e){this.root=e;const t=globalThis.MutationObserver;this.observer="function"==typeof t?new t(e=>this.handleMutations(e)):null,this.observer?.observe(e,{childList:!0,subtree:!0})}add(e){this.knownSessions.has(e)||(this.knownSessions.add(e),this.sessionRefs.add(new WeakRef(e)))}handleMutations(e){const t=[],n=[];for(const o of e)t.push(...Array.from(o.removedNodes)),n.push(...Array.from(o.addedNodes));for(const e of Array.from(this.sessionRefs)){const o=e.deref();void 0!==o?o.handleMutations(this.root,t,n):this.sessionRefs.delete(e)}}}const Nn=new WeakMap;class vn{records=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(e=null){null!==e&&this.observe(e)}initialize(e,t={}){const n=t.registerAddress??!0,o={registerAddress:n,registerPathInfo:t.registerPathInfo??n,applyOnReconnect:t.applyOnReconnect??!0},s=[];for(const t of e){const e=this.remember(t,o),n=gn.get(e);void 0===n||"disposed"===n.phase||"failed"===n.phase?(this.start(e,o),s.push(e)):(this.observe(n.anchor),o.registerAddress&&null===n.address&&(n.options.registerAddress=!0,this.registerAddress(n)),"active"===n.phase&&this.settleInitialRecord(n),this.settleConnectedSnapshot(n))}return s.filter(e=>this.shouldApplyState(e))}shouldApplyState(e){if(!n.enableDirectionalInitialSync)return un(e)&&fn(e),!0;const t=gn.get(e);return void 0===t||t.session!==this||(!t.options.registerAddress||"waiting-definition"===t.phase||("active"===t.phase&&this.settleInitialRecord(t),"state"===t.resolvedAuthority))}getRecord(e){const t=gn.get(e);return t?.session===this?t:null}addTeardown(e,t){const n=gn.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(n.teardowns.add(t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=M();null===s&&j(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e);const r={node:e,active:!0,cancel:null};let i=this.deferredByNode.get(e);void 0===i&&(i=new Set,this.deferredByNode.set(e,i)),i.add(r),this.deferred.add(r);const a=()=>!!r.active&&(r.active=!1,i?.delete(r),this.deferred.delete(r),!0);return r.cancel=ln(s).wait(t,()=>{if(a())try{O(s,e),n()}catch(e){o(e)}},e=>{a()&&o(e)}),()=>{a()&&r.cancel?.()}}disposeBinding(e){const t=gn.get(e);void 0!==t&&t.session===this&&this.disposeRecord(t)}dispose(){for(const e of Array.from(this.records))this.disposeRecord(e);for(const e of Array.from(this.deferred))e.active=!1,e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}observe(e){const t=function(e){const t=e.getRootNode();return function(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}(t)?t:null}(e);null!==t&&function(e){let t=Nn.get(e);return void 0===t&&(t=new wn(e),Nn.set(e,t)),t}(t).add(this)}handleMutations(e,t,n){for(const n of t)yn(n,t=>{if(e.contains(t))return;const n=this.knownBindingsByNode.get(t);if(void 0!==n)for(const e of n.values())this.disposeBinding(e);const o=this.deferredByNode.get(t);if(void 0!==o)for(const e of Array.from(o))e.active=!1,e.cancel?.(),o.delete(e),this.deferred.delete(e)});const o=[];for(const t of n)yn(t,t=>{if(!e.contains(t))return;const n=this.knownBindingsByNode.get(t);if(void 0!==n)for(const e of n.values()){const t=gn.get(e);if("active"===t?.phase){this.settleConnectedSnapshot(t);continue}if("disposed"!==t?.phase)continue;const n=this.optionsByBinding.get(e);if(void 0!==n)try{this.start(e,n),n.applyOnReconnect&&this.shouldApplyState(e)&&o.push(e)}catch{}}});o.length>0&&zo(o)}remember(e,t){const n=e.replaceNode;let o=this.knownBindingsByNode.get(n);void 0===o&&(o=new Map,this.knownBindingsByNode.set(n,o));const s=function(e){const t=e.inFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|"),n=e.outFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.bindingType,e.propName,e.propModifiers.join(","),e.stateName,e.statePathName,t,n,e.uuid??""].join("\0")}(e),r=o.get(s);if(void 0!==r){const e=this.optionsByBinding.get(r);return void 0!==e&&(e.registerAddress||=t.registerAddress,e.registerPathInfo||=t.registerPathInfo,e.applyOnReconnect||=t.applyOnReconnect),r}return o.set(s,e),this.optionsByBinding.set(e,{...t}),e}start(e,t){!function(e){const t=e.node,n=e.replaceNode;t!==n&&null!==t.parentNode&&t.parentNode.replaceChild(n,t)}(e);const n=this.optionsByBinding.get(e)??{...t},o={id:++hn,info:e,generation:++mn,phase:"discovered",teardowns:new Set,session:this,anchor:e.replaceNode,options:n,address:null,pendingDefinitions:0,initialPolicy:null,resolvedAuthority:null,initialSettled:!1,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0};gn.set(e,o),this.records.add(o),this.observe(o.anchor);try{o.phase="attaching",this.attachListeners(o),o.options.registerAddress&&this.registerAddress(o),0===o.pendingDefinitions&&(o.phase="active")}catch(e){throw o.phase="failed",this.runTeardowns(o),this.records.delete(o),e}}attachListeners(e){const t=e.info;!function(e){if(!e.propName.startsWith("on"))return!1;const t=Tt(e);let n=Pt.get(t);void 0===n&&(n=kt(e.stateName,e.statePathName,e.propModifiers,e.statePathInfo),Pt.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),$t.add(t,e),!0}(t)?"eventToken"!==t.propSegments[0]?(Dt(t)&&e.teardowns.add(()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf("ro")){const t=Ot(e),n=Mt(e,t),o=Ct.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Et.countOf(n)&&(Et.remove(n,e)&&Ct.delete(n),!0))}return!1}(t)),bt(t)&&e.teardowns.add(()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf("ro")){const t=gt(e),n=mt(e,t),o=pt.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==ht.countOf(n)&&(ht.remove(n,e)&&pt.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(n.enableDirectionalInitialSync&&Wt(t.node,t.propName)&&-1===t.propModifiers.indexOf("ro")){const n=function(e,t,n){let o=en.get(e);void 0===o&&(o=new Map,en.set(e,o));let s=o.get(t);return void 0===s&&(s=new Set,o.set(t,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(t),0===o?.size&&en.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});e.teardowns.add(n)}!function(e){const t=E(e.node);if(null!==t){const e=M(),n=e?.get(t);if(void 0===n)return void(null===e&&j(`CustomElementRegistry is unavailable for <${t}>.`))}if(Wt(e.node,e.propName)&&-1===e.propModifiers.indexOf("ro")){const t=on(e),n=sn(e),o=nn(e,t,null!==n);let s=Qt.get(o);void 0===s&&(s=rn(e.stateName,e.propName,e.statePathName,e.inFilters,n),Qt.set(o,s)),e.node.addEventListener(t,s),Zt.add(o,e)}}(t),e.teardowns.add(()=>function(e){const t=E(e.node);if(null!==t){const e=M(),n=e?.get(t);if(void 0===n)return}if(Wt(e.node,e.propName)&&-1===e.propModifiers.indexOf("ro")){const t=on(e),n=nn(e,t,null!==sn(e)),o=Qt.get(n);if(void 0===o)return;e.node.removeEventListener(t,o),Zt.remove(n,e)&&Qt.delete(n)}}(t))})):this.attachAfterDefinition(e,()=>{It(t)&&e.teardowns.add(()=>function(e){if("eventToken"!==e.propSegments[0])return!1;const t=xt.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),xt.delete(e),!0)}(t))}):e.teardowns.add(()=>function(e){if(!e.propName.startsWith("on"))return!1;const t=Tt(e),n=Pt.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==$t.countOf(t)&&($t.remove(t,e)&&Pt.delete(t),!0)}(t))}attachAfterDefinition(e,t){const n=E(e.info.node);if(null===n)return void t();const o=M();if(null===o&&j(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void t();e.phase="waiting-definition",e.pendingDefinitions+=1;const s=e.generation,r=ln(o).wait(n,()=>{if(this.isAlive(e,s))try{O(o,e.info.node),t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e))}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))});e.teardowns.add(r)}settleInitialRecord(e){if(n.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=fn(e.info),n=pn(e.info,t.authority);if(e.initialPolicy=t,e.resolvedAuthority=n,e.initialSettled=!0,e.phase="active",!t.observable)return;if("connect"===t.syncOn&&e.info.node instanceof HTMLElement&&!e.info.node.isConnected)return void(e.observationPending=!0);this.readProducerSnapshot(e,"call"===t.syncOn)}catch(t){throw e.phase="failed",this.runTeardowns(e),this.records.delete(e),t}}}readProducerSnapshot(e,t){if(!this.isAlive(e,e.generation))return;const n=e.info.node,o=e.info.propName;if(!(o in n))return;const s=e.eventSequence,r=n[o];e.observationPending=!1,t&&e.eventSequence!==s||(e.hasProducerValue=!0,e.producerValue=r,"element"===e.resolvedAuthority&&function(e,t){let n=t;for(const t of e.inFilters)n=t.filterFn(n);const o=$s(e.node.getRootNode(),e.stateName);null===o&&j(`State element with name "${e.stateName}" not found for initial binding sync.`);const s=Ie(e.node);o.createState("writable",t=>{t[ke](s,()=>{t[e.statePathName]=n})})}(e.info,r))}settleConnectedSnapshot(e){if(n.enableDirectionalInitialSync&&e.observationPending&&e.info.node instanceof HTMLElement&&e.info.node.isConnected)try{this.readProducerSnapshot(e,!1)}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}}registerAddress(e){if(null!==e.address)return;const t=e.info,n=Qe(t);if(ot(n,t),e.address=n,e.teardowns.add(()=>{null!==e.address&&(st(e.address,t),e.address=null,ut(t),Ze(t))}),!e.options.registerPathInfo)return;const o=$s(t.replaceNode.getRootNode(),t.stateName);null===o&&j(`State element with name "${t.stateName}" not found for binding.`),"event"!==t.bindingType&&o.setPathInfo(t.statePathName,t.bindingType)}isAlive(e,t){return e.generation===t&&gn.get(e.info)===e&&"disposed"!==e.phase&&"failed"!==e.phase}disposeRecord(e){"disposed"!==e.phase&&(e.phase="disposed",this.runTeardowns(e),this.records.delete(e))}runTeardowns(e){const t=Array.from(e.teardowns).reverse();e.teardowns.clear();for(const e of t)try{e()}catch{}}}function Sn(e){let t=bn.get(e);return void 0===t&&(t=new vn(e),bn.set(e,t)),t}function xn(e){return gn.get(e)?.session??null}const In=new WeakMap;function An(e,t){const n=In.get(e);return!!n&&!0===n.get(t)}function _n(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const Pn=Object.freeze([]);const $n=new WeakMap;const Tn=new WeakMap;function kn(e){return Tn.get(e)??[]}function Cn(e,t){Tn.set(e,t)}Set.prototype.difference||(Set.prototype.difference=function(e){const t=new Set(this);for(const n of e)t.delete(n);return t}),Set.prototype.intersection||(Set.prototype.intersection=function(e){const t=new Set;for(const n of e)this.has(n)&&t.add(n);return t});let En=0;function Mn(){return`u${(En++).toString(36)}`}let On=0;class Dn{uuid=Mn();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;constructor(e,t){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._index=t,this._version=On}get index(){return this._index}set index(e){this._index=e,this._version=++On,this.indexes[this.position]=e}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=On),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(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function Rn(e,t){return new Dn(e,t)}const Ln=new WeakMap;function Wn(e){return Ln.get(e)||null}function Bn(e,t){null!==t?Ln.set(e,t):Ln.delete(e)}const jn=new WeakMap,Fn=Object.freeze([]),zn=new Set;function qn(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:Fn,s=Array.isArray(n)&&n.length>0?n:Fn,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Fn,o=Array.isArray(t)&&t.length>0?t:Fn;let s=jn.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Wn(o)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:zn,deleteIndexSet:new Set(i),addIndexSet:zn};let t=Wn(s);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=Rn(e,n);t.push(o)}}return a={oldIndexes:i,newIndexes:t,changeIndexSet:zn,deleteIndexSet:zn,addIndexSet:new Set(t)}}if(function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}(o,s))return a={oldIndexes:i,newIndexes:i,changeIndexSet:zn,deleteIndexSet:zn,addIndexSet:zn};if(null!==t)return function(e,t){const n=new Set(t),o=new Set(e),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let t=0;t<e.length;t++)a.set(e[t],t);for(let e=0;e<t.length;e++){const n=t[e];r.has(n)||a.get(n)!==e&&s.add(n)}return{oldIndexes:e,newIndexes:t,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,t);t=[];const n=new Map;for(let e=0;e<o.length;e++){const t=o[e];let s=n.get(t);s||(s=[],n.set(t,s)),s.push(e)}const r=new Set,c=new Set;for(let o=0;o<s.length;o++){const a=s[o],l=n.get(a),d=l&&l.length>0?l.shift():void 0;if(void 0===d){const n=Rn(e,o);t.push(n),c.add(n)}else{const e=i[d];d!==o&&r.add(e),t.push(e)}}return a={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:c}}finally{void 0!==a&&(!function(e,t,n){let o=jn.get(e);o||(o=new WeakMap,jn.set(e,o)),o.set(t,n)}(o,s,a),Bn(s,a.newIndexes))}}(e,t,n);return function(e){for(let t=0;t<e.length;t++)e[t].index!==t&&(e[t].index=t)}(o.newIndexes),o}function Un(e){if(0===e.changeIndexSet.size||e.addIndexSet.size===e.newIndexes.length)return null;const t=new Map;for(let n=0;n<e.oldIndexes.length;n++)t.set(e.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of e.newIndexes){if(e.addIndexSet.has(i))continue;const a=t.get(i);if(void 0===a)return null;a<s&&(r=!1),s=a,n.push(i),o.push(a)}if(r)return null;const i=function(e){const t=e.length,n=[],o=new Array(t).fill(-1);for(let s=0;s<t;s++){const t=e[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;e[n[o]]<t?r=o+1:i=o}r>0&&(o[s]=n[r-1]),n[r]=s}const s=[];let r=n.length>0?n[n.length-1]:-1;for(;r>=0;)s.push(r),r=o[r];return s.reverse(),s}(o),a=new Set;for(const e of i)a.add(n[e]);return a}const Vn=new WeakMap;function Hn(e){return Vn.get(e)??[]}function Gn(e,t){Vn.set(e,t)}const Jn=new WeakMap;function Kn(e){return Jn.get(e)??null}function Yn(e,t){Jn.set(e,t)}const Xn=new WeakMap;function Qn(e){return Xn.get(e)??[]}function Zn(e,t){Xn.set(e,t)}function eo(e,t){const n=Qn(e);for(const e of n)Ae(e,t)}function to(e,t,n){eo(e,t);const o=Hn(e),s=Kn(e);null!==s&&s.initialize(o,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});for(const e of o){if(null===s){ot(Qe(e),e)}(null===s||s.shouldApplyState(e))&&Fo(e,n)}}function no(e){if(!e.mounted)return;const t=Hn(e),n=Kn(e);for(const e of t)if(null!==n)n.disposeBinding(e);else{st(Qe(e),e)}!function(e){const t=Qn(e);for(const e of t)Ae(e,null)}(e)}const oo=new WeakMap,so=Object.freeze(new Set);function ro(e,t){const n=oo.get(e);n?n.add(t):oo.set(e,new Set([t]))}function io(e){const t=oo.get(e);return void 0!==t?t:so}const ao=new Set(["if","elseif","else","for"]);class co{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;constructor(e){this._content=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(e){for(const t of this._childNodeArray)e.appendChild(t);this._mounted=!0}mountAfter(e){const t=e.parentNode,n=e.nextSibling;if(t)for(const e of this._childNodeArray)t.insertBefore(e,n);this._mounted=!0}unmount(){Kn(this)?.dispose();for(const e of this._childNodeArray)null!==e.parentNode&&e.parentNode.removeChild(e);const e=Hn(this);for(const t of e){if(ao.has(t.bindingType)){const e=io(t.node);for(const t of e)t.unmount()}ut(t),Ze(t)}this._mounted=!1}}function lo(e){const t=document.createDocumentFragment(),n=new co(t);return n._childNodeArray=e,n._firstNode=e.length>0?e[0]:null,n._lastNode=e.length>0?e[e.length-1]:null,n._mounted=!0,n}function uo(e){void 0!==e.uuid&&null!==e.uuid||j("BindingInfo.uuid is null.");const t=ge(e.uuid);t||j(`Fragment with UUID "${e.uuid}" not found.`);const n=document.importNode(t.fragment,!0),o=function(e,t){const[n,o]=function(e,t){const n=[],o=[];for(const s of t){const t=q(e,s.nodePath);if(null===t&&j(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),we.has(t))continue;const r=Ne(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new vn,r=s.initialize(o,{registerAddress:!1,applyOnReconnect:!1});return{nodes:n,bindingInfos:r,bindingSession:s}}(n,t.nodeInfos),s=new co(n);Yn(s,o.bindingSession),Gn(s,o.bindingInfos);const r=[];for(const e of o.bindingInfos)e.statePathName in p&&r.push(e);return Cn(s,r),Zn(s,o.nodes),ro(e.node,s),s}const fo=new WeakMap,po=new WeakMap,ho=new WeakMap,mo=new WeakMap;function go(e,t,n){So(e,t,n)}function bo(e,t){fo.set(e,t)}function yo(e){return ho.get(e.node)||[]}function wo(e,t){let n=ho.get(e.node);void 0===n&&(n=[],ho.set(e.node,n)),n.length<1e3?n.push(t):function(e,t){const n=oo.get(e);n&&(n.delete(t),0===n.size&&oo.delete(e))}(e.node,t)}function No(e,t){if(null===t)return!1;if(e.nextSibling===t)return!0;const n=e.compareDocumentPosition(t);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}function vo(e,t){let n=po.get(e);if(void 0===n)return null;const o=n.get(t);return void 0===o?null:o}function So(e,t,n){let o=po.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,po.set(e,o)}null===n?o.delete(t):o.set(t,n)}const xo=new WeakMap;function Io(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function Ao(t,o,s){const r=t.node.isConnected,i=Boolean(s);let a;const c=io(t.node);a=0===c.size?uo(t):c.values().next().value;const l=e(),d=t.uuid??"",u=t.bindingType;try{if(i||(n.debug&&console.log(`unmount if content : ${Io(t)}`),no(a),a.unmount()),i){if(n.debug&&console.log(`mount if content : ${Io(t)}`),l){const e=document.createComment(`@@wcs-${u}-start:${d}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),a.mountAfter(e);const n=document.createComment(`@@wcs-${u}-end:${d}:${t.statePathName}`),o=a.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}else a.mountAfter(t.node);to(a,Ie(t.node),o)}}finally{xo.set(t.node,r)}}const _o=new WeakMap;function Po(e){return _o.get(e)??[]}const $o=new Set;const To={value(e,t){"TEXTAREA"===e.tagName?e.textContent=String(t??""):e.setAttribute("value",String(t??""))},checked(e,t){t?e.setAttribute("checked",""):e.removeAttribute("checked")},selected(e,t){t?e.setAttribute("selected",""):e.removeAttribute("selected")},disabled(e,t){t?e.setAttribute("disabled",""):e.removeAttribute("disabled")},selectedIndex(e,t){const n=e.querySelectorAll("option"),o=Number(t);for(let e=0;e<n.length;e++)e===o?n[e].setAttribute("selected",""):n[e].removeAttribute("selected")}};function ko(t,o,s){if(void 0===s)return void(n.debug&&console.debug("Skipped property write: state value is undefined.",{element:t.node,propSegments:t.propSegments,statePathName:t.statePathName}));const r=t.node,i=t.propSegments;if(1===i.length){const c=i[0];if(r[c]!==s){const e=()=>{let e=!1;try{r[c]=s,e=!0}catch(e){n.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:e})}if(e){const e=function(e,t){const n=E(e);if(null===n)return null;const o=M()?.get(n);if(void 0===o)return null;const s=D(e)?.declaredInputs.get(t);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==e)try{!function(e,t,n){if(null==n)return void e.removeAttribute(t);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);e.setAttribute(t,o)}(r,e,s)}catch(t){n.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:s,error:t})}}};if(n.enablePropagationContext&&Wt(r,c)){const n=qt(r,c,t.stateName,t.statePathName),i=Ut(n,"to-element"),a=o?.propagationContextByBinding?.get(t)??Kt()??Ht(n);if(a.visitedEdges.has(i))null!==et&&et({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:i,node:r,member:c});else{const t=Gt(a,i);Yt(t,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:Ft++,writtenValue:n};Xt.push({receipt:i,node:e});try{return r()}finally{Xt.pop()}}(r,c,s,n,t.transactionId,e))}}else e()}if(e()){const e=To[c];e?e(r,s):(!function(e,t,n){let o=_o.get(e);o||(o=[],_o.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,c,s),a=r,$o.add(a))}return}var a;const c=i[0];let l=r[c];for(let e=1;e<i.length-1;e++){const t=i[e];if(null==l)return;l=l[t]}const d=l[i[i.length-1]];if(d!==s){if(Object.isFrozen(l))return void(n.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:d,newValue:s}));try{l[i[i.length-1]]=s}catch(e){n.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:d,newValue:s,error:e})}}}const Co=new WeakSet;function Eo(e,t,n){const o=e.node,s=e.propSegments;s.length<=1&&j(`Invalid propSegments for web component binding: ${s.join(".")}`);const[r,...i]=s,a=o[r];void 0===a&&j(`Property "${r}" not found on web component.`),a[i.join(".")]=n}function Mo(e,t){const n=dt(t);if(n.pathInfo.path in p){const e=Ie(t.node);return null===e&&j(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&j("ListIndex not found for loopContext:");const n=p[t];void 0===n&&j(`Invalid index name: ${t}`);const o=e.listIndex.at(n);return null===o&&j(`Index not found at position ${n} for loopContext:`),o.index}(e,n.pathInfo.path)}return e[Ce](n)}const Oo=new WeakSet;function Do(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const Ro={class:function(e,t,n){const o=e.node,s=e.propSegments[1];"boolean"!=typeof n&&j("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},attr:function(e,t,n){const o=e.node,s=e.propSegments[1];o.getAttribute(s)!==n&&o.setAttribute(s,n)},style:function(e,t,n){const o=e.propSegments[1],s=e.node.style;s[o]!==n&&(s[o]=n)},command:function(e,t,n){_t(n)||j("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=$n.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||j('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=E(e);if(null===t)return null;const n=M()?.get(t);return void 0===n&&j(`Custom element <${t}> is not defined for command binding.`),D(e)}(r);null===a&&j(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||j(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.`),s&&(s.unsubscribe(),$n.delete(e));const c=new WeakRef(r);let l=null;l=o.subscribe((...t)=>{const n=c.deref();if(!n||!n.isConnected)return l?.(),void $n.delete(e);const o=n[i];return"function"!=typeof o&&j(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),$n.set(e,{token:o,unsubscribe:l,elementRef:c})}},Lo={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!Co.has(t.replaceNode)){Co.add(t.replaceNode);const e=t.replaceNode.parentNode;if(e){const n=t.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);e.insertBefore(o,t.replaceNode),e.insertBefore(s,t.replaceNode.nextSibling)}}},for:function(t,n,o){const s=t.statePathInfo,r=Ye(t),i=Qe(t),a=Pe(i),c=qn(r,a,o);if(n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]),Array.isArray(a)&&a.length===c.deleteIndexSet.size&&c.deleteIndexSet.size>0&&null!==t.node.parentNode){let e=mo.get(t.node);if(void 0===e){const n=fo.get(t.node)||t.node;e=function(e,t){let n=e.previousSibling,o=t.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),mo.set(t.node,e)}if(e){const e=t.node.parentNode;e.textContent="",e.appendChild(t.node)}}for(const e of c.deleteIndexSet){const n=vo(t.node,e);null!==n&&(no(n),n.unmount(),wo(t,n),So(t.node,e,null))}let d=t.node;const u=T(s.path+"."+l),f=n.stateElement.loopContextStack,p=Un(c);let h=null;c.newIndexes.length==c.addIndexSet.size&&c.newIndexes.length>0&&d.isConnected&&(h=document.createDocumentFragment(),Ve(h,n.rootNode));const m=e(),g=t.uuid??"";for(const e of c.newIndexes){let o;if(c.addIndexSet.has(e)){const r=ct(u,e);f.createLoopContext(r,r=>{const i=yo(t);if(o=i.pop(),void 0===o&&(o=uo(t)),null!==h)m&&h.appendChild(document.createComment(`@@wcs-for-start:${g}:${s.path}:${e.index}`)),o.appendTo(h),m&&h.appendChild(document.createComment(`@@wcs-for-end:${g}:${s.path}:${e.index}`));else{if(d.nextSibling!==o.firstNode){if(m){const t=document.createComment(`@@wcs-for-start:${g}:${s.path}:${e.index}`);d.parentNode.insertBefore(t,d.nextSibling),d=t}o.mountAfter(d)}if(m){const t=document.createComment(`@@wcs-for-end:${g}:${s.path}:${e.index}`),n=o.lastNode??d;n.parentNode.insertBefore(t,n.nextSibling)}}to(o,r,n)}),void 0===o&&j(`Content not found for ListIndex: ${e.index} at path "${s.path}"`)}else{if(o=vo(t.node,e),c.changeIndexSet.has(e)){const e=kn(o);for(const t of e)Fo(t,n)}null===o&&j(`Content not found for ListIndex: ${e.index} at path "${s.path}"`);null!==p&&p.has(e)&&No(d,o.firstNode)||d.nextSibling===o.firstNode||o.mountAfter(d)}d=o.lastNode||d,So(t.node,e,o)}fo.set(t.node,d),null!==h&&(t.node.parentNode.insertBefore(h,t.node.nextSibling),Ve(h,null))},if:Ao,else:Ao,elseif:Ao,radio:function(e,t,n){const o=e.node,s=_n(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=_n(o.value,e.inFilters),r=Array.isArray(n)?n:Pn;o.checked=r.includes(s)}},Wo=new WeakMap,Bo=new WeakMap;function jo(e,t){const n=_n(Mo(t.state,e),e.outFilters);if(!0===Bo.get(e))return void t.deferredSelectBindings.push({binding:e,value:n});let o=Wo.get(e);if(void 0===o){if(Wo.has(e))return An(e.replaceNode,t.stateElement)?(o=Eo,Wo.set(e,o)):o=ko,void o(e,t,n);if(o=Lo[e.bindingType],void 0===o){const n=e.propSegments[0];if(o=Ro[n],Wo.set(e,o),void 0===o){E(e.replaceNode)?An(e.replaceNode,t.stateElement)?(o=Eo,Wo.set(e,o)):o=ko:(o=ko,Wo.set(e,o))}}if(o===ko){if("SELECT"===e.node.tagName){const o=e.propSegments[0];if("value"===o||"selectedIndex"===o)return t.deferredSelectBindings.push({binding:e,value:n}),void Bo.set(e,!0)}}o(e,t,n)}else o(e,t,n)}function Fo(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=Qe(e);if(t.updatedAbsAddressSetByStateElement.has(t.stateElement)){t.updatedAbsAddressSetByStateElement.get(t.stateElement).add(n)}else t.updatedAbsAddressSetByStateElement.set(t.stateElement,new Set([n]))}const n=xn(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;const o=E(e.replaceNode);if(o&&void 0===M()?.get(o))return void function(e,t){if(Oo.has(e))return;Oo.add(e);const n=()=>{Oo.delete(e);const t=xn(e);(null===t||t.shouldApplyState(e))&&zo([e])},o=n=>{Oo.delete(e),Do(t,n)},s=xn(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{Oo.delete(e),r()})||(Oo.delete(e),r()))}const r=M();if(null===r)return Oo.delete(e),void Do(t,new Error("CustomElementRegistry is unavailable."));ln(r).wait(t,()=>{e.replaceNode.isConnected?n():Oo.delete(e)},o)}(e,o);if(!0===t.sameRootVerified&&e.stateName===t.stateName)return void jo(e,t);let s=e.replaceNode.getRootNode();if(s instanceof DocumentFragment&&!(s instanceof ShadowRoot)&&(s=He(s),null===s&&j("Root node for fragment not found for binding.")),e.stateName!==t.stateName||s!==t.rootNode){const n=$s(s,e.stateName);null===n&&j(`State element with name "${e.stateName}" not found for binding.`),n.createState("readonly",o=>{const r={stateName:e.stateName,rootNode:s,stateElement:n,state:o,appliedBindingSet:t.appliedBindingSet,newListValueByAbsAddress:t.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:t.updatedAbsAddressSetByStateElement,deferredSelectBindings:t.deferredSelectBindings};jo(e,r)})}else jo(e,t)}function zo(e,t){let o=0;const s=new Set,r=new Map,i=new Map,a=[];for(;o<e.length;){let c=e[o];const l=c.stateName;if(!1===c.replaceNode.isConnected){n.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${c.bindingType} ${c.statePathName} on ${c.node.nodeName}`,c),o++;continue}let d=c.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=He(d),null===d&&j("Root node for fragment not found for binding."));const u=$s(d,l);null===u&&j(`State element with name "${l}" not found for binding.`),u.createState("readonly",n=>{const f={rootNode:d,stateName:l,stateElement:u,state:n,appliedBindingSet:s,newListValueByAbsAddress:r,updatedAbsAddressSetByStateElement:i,deferredSelectBindings:a,sameRootVerified:!0,propagationContextByBinding:t};for(;;){Fo(c,f),o++;const t=e[o];if(!t)break;const n=t.replaceNode.getRootNode();if(t.stateName!==l||n!==f.rootNode)break;c=t}})}for(const{binding:e,value:n}of a)ko(e,{propagationContextByBinding:t},n);for(const[e,t]of r.entries())$e(e,t);for(const[e,t]of i.entries())e.createState("writable",e=>{e[Re](Array.from(t))})}function qo(e,t){const[n,o,s]=ve(e),r=Sn(e);for(const e of n)Ae(e,t);zo(r.initialize(o)),function(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=Se(o);0!==e.length&&(Ae(o.node,t),zo(n.initialize(e)))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}(s,t,r)}const Uo=/\{\{\s*(.+?)\s*\}\}/g,Vo=new Set(["SCRIPT","STYLE"]);function Ho(e){if(!n.enableMustache)return;!function(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[];for(;t.nextNode();)n.push(t.currentNode);for(const e of n)e.parentElement&&Vo.has(e.parentElement.tagName)||Go(e)}(e);const t=Array.from(e.querySelectorAll("template"));for(const e of t)if("http://www.w3.org/2000/svg"===e.namespaceURI){const t=document.createElement("template"),n=Array.from(e.childNodes);for(let e=0;e<n.length;e++){const o=n[e];t.content.appendChild(o)}for(const n of e.attributes)t.setAttribute(n.name,n.value);e.replaceWith(t),Ho(t.content)}else Ho(e.content)}function Go(e){const t=e.data;if(Uo.lastIndex=0,!Uo.test(t))return;Uo.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=Uo.exec(t));){o.index>s&&n.appendChild(document.createTextNode(t.slice(s,o.index)));const e=o[1];n.appendChild(document.createComment(`@@: ${e}`)),s=o.index+o[0].length}s<t.length&&n.appendChild(document.createTextNode(t.slice(s))),e.parentNode.replaceChild(n,e)}let Jo;function Ko(){if(Jo)return Jo;const e=[],t=ne("not",e)(ee);return Jo={filterName:"not",args:e,filterFn:t},Jo}const Yo=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Xo(e,t){const n=t+c+l,o=e.indexOf("|"),s=e.indexOf("@");let r,i;if(-1!==o?(r=e.slice(0,o).trim(),i=e.slice(o)):-1!==s?(r=e.slice(0,s).trim(),i=e.slice(s)):(r=e.trim(),i=""),"."===r)r=n;else{if(!r.startsWith("."))return e;r=n+c+r.slice(1)}return i.length>0?r+i:r}function Qo(e,t){const n=Yo.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+Xo(s,t)+r}function Zo(e,t){const n=e.split(";");let o=!1;const s=n.map(e=>{const n=e.trim();if(0===n.length)return e;const s=n.indexOf(":");if(-1===s)return e;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=Xo(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function es(e,t){return Zo(e,t)}function ts(e,t){const o=n.bindAttributeName,s=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const e=s.currentNode;if(e.nodeType===Node.COMMENT_NODE){const n=e;n.data=Qo(n.data,t);continue}const n=e;if(n instanceof HTMLTemplateElement)continue;const r=n.getAttribute(o);if(null!==r){const e=Zo(r,t);e!==r&&n.setAttribute(o,e)}}}function ns(e){let t=e;const n=[];for(;null!==t.parentNode;){const e=Array.from(t.parentNode.childNodes).indexOf(t);n.unshift(e),t=t.parentNode}return n}function os(e){const t=[],n=ye(e);for(const e of n){const n=be(e);t.push({nodePath:ns(e),parseBindTextResults:n})}return t}function ss(e){const t=Array.from(e.childNodes);for(const n of t)if(n.nodeType===Node.TEXT_NODE){""===(n.textContent||"").trim()&&e.removeChild(n)}}const rs=new Map([["for",n.commentForPrefix],["if",n.commentIfPrefix],["elseif",n.commentElseIfPrefix],["else",n.commentElsePrefix]]),is=Ko();function as(e,t){const n=t.outFilters;return{...t,outFilters:[...n,is],bindingType:e}}function cs(e,t,n,o){ss(t),"string"==typeof o&&ts(t,o),ls(e,t,o);return{fragment:t,parseBindTextResult:n,nodeInfos:os(t)}}function ls(e,t,o){const s=n.commentElsePrefix,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode(e){const t=e;if("template"===t.tagName.toLowerCase()){if((t.getAttribute(n.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let i=null;const a=[],c=[];for(;r.nextNode();){const e=r.currentNode;c.push(e)}for(const t of c){let r=t.getAttribute(n.bindAttributeName)||"";"string"==typeof o&&(r=es(r,o));let c=le(r)[0];const l=rs.get(c.bindingType);if(void 0===l)continue;const d=c.bindingType,u=t.content,f=Mn();let p=null;const h="for"===d?c.statePathName:o;if("else"===d){null===i&&j("'else' binding found without preceding 'if' or 'elseif' binding."),c=as("else",i.parseBindTextResult),p=cs(e,u,c,h),me(f,e,p);const n=a.at(-1),o=document.createComment(`@@${l}:${f}`);void 0!==n?(t.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:ns(o),parseBindTextResults:be(o)})):t.replaceWith(o)}else if("elseif"===d){null===i&&j("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=cs(e,u,c,h),me(f,e,p);const n=document.createComment(`@@${l}:${f}`),o=Mn(),r={fragment:document.createDocumentFragment(),parseBindTextResult:as("else",i.parseBindTextResult),nodeInfos:[]};r.fragment.appendChild(n),r.nodeInfos.push({nodePath:ns(n),parseBindTextResults:be(n)}),me(o,e,r);const d=a.at(-1);a.push(r);const m=document.createComment(`@@${s}:${o}`);void 0!==d?(t.remove(),d.fragment.appendChild(m),d.nodeInfos.push({nodePath:ns(m),parseBindTextResults:be(m)})):t.replaceWith(m)}else{p=cs(e,u,c,h),me(f,e,p);const n=document.createComment(`@@${l}:${f}`);t.replaceWith(n)}"if"===d?(a.length=0,i=p):"elseif"===d?i=p:"else"===d&&(i=null,a.length=0)}}async function ds(e){const t=e.querySelectorAll(n.tagNames.state),o=[];await customElements.whenDefined(n.tagNames.state);for(const e of t){const t=e;o.push(t.initializePromise)}await Promise.all(o)}async function us(e){if(e===document)await ds(document),Ho(document),ls(document,document),qo(document.body,null);else{const t=e;t.host.hasAttribute(n.bindAttributeName)&&await a(t.host),await ds(t),Ho(t),ls(t,t),qo(t,null)}}const fs="1.21.2",ps="undefined"==typeof HTMLElement?class{}:HTMLElement,hs=/^@@wcs-(?:for|if|elseif|else):[^-]/,ms=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,gs=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,bs=/^@@wcs-text-start:(.+)$/;function ys(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class ws extends ps{_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(e){return this.templates.get(e)??null}verifyVersion(){const e=this.version;if(!e)return!0;const t=e.split("."),n=fs.split(".");return t[0]===n[0]&&t[1]===n[1]}setStateData(e){this._stateData=e}setHydrateProps(e){this._hydrateProps=e}_loadStateData(){const e=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}_loadTemplates(){const e=new Map,t=this.querySelectorAll("template[id]");for(const n of t){const t=n.getAttribute("id");t&&e.set(t,n)}return e}_loadHydrateProps(){const e=this.querySelector("script[data-wcs-ssr-props]");if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}static findByName(e,t){const o=n.tagNames.ssr,s=e instanceof Element?e:e instanceof Document?e.documentElement:null;if(!s)return null;return s.querySelector(`${o}[name="${t}"]`)}static extractStateData(e){const t=e.__state;if(!t||"object"!=typeof t)return{};const n={};for(const[e,o]of Object.entries(t))e.startsWith("$")||"function"==typeof o||(n[e]=o);return n}static buildContent(e,t){const o=document.createElement("script");o.setAttribute("type","application/json"),o.textContent=ys(JSON.stringify(t)),e.appendChild(o);const s=Array.from(he.keys());for(const t of s){const o=ge(t);if(!o)continue;const s=document.createElement("template");s.setAttribute("id",t);const r=o.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(n.bindAttributeName,i);const a=o.fragment.cloneNode(!0);s.content.appendChild(a),e.appendChild(s)}const r=Array.from($o);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],o=Po(n);if(0===o.length)continue;const s=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",s);const i={};for(const e of o)i[e.propName]=e.value;t[s]=i}if(Object.keys(t).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=ys(JSON.stringify(t)),e.appendChild(n)}}$o.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(ms.test(e.data)||gs.test(e.data))&&n.push(e)}for(const e of n)e.remove()}static removeStructuralComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;hs.test(e.data)&&n.push(e)}for(const e of n)e.remove()}static restoreTextBindings(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode,o=bs.exec(e.data);o&&n.push({comment:e,path:o[1]})}for(const{comment:e,path:t}of n){const n=document.createComment(`@@: ${t}`);e.parentNode.insertBefore(n,e);let o=e.nextSibling;e.remove();const s=`@@wcs-text-end:${t}`;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=e}}}static cleanupDom(e){const t=document.body,o=e.querySelectorAll(n.tagNames.ssr),s=new Map;for(const e of o){const t=e.querySelectorAll("template[id]");for(const e of t){const t=e.getAttribute("id");t&&s.set(t,e)}}const r=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const e=r.currentNode;ms.test(e.data)&&i.push(e)}for(const e of i){const t=ms.exec(e.data),n=`@@wcs-${t[1]}-end:${t[2]}`;let o=e.nextSibling;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===n){o.remove();break}o.remove(),o=e}e.remove()}ws.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),c=[];for(;a.nextNode();){const e=a.currentNode;if(hs.test(e.data)){const t=e.data.split(":")[1];c.push({comment:e,uuid:t})}}for(const{comment:e,uuid:t}of c){const o=s.get(t);if(o){const t=document.createElement("template"),s=o.getAttribute(n.bindAttributeName);s&&t.setAttribute(n.bindAttributeName,s);const r=document.importNode(o.content,!0);if(r.childNodes.length>0)t.content.appendChild(r);else for(const e of Array.from(o.childNodes))t.content.appendChild(document.importNode(e,!0));e.parentNode.replaceChild(t,e)}}const l=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of l)e.removeAttribute("data-wcs-ssr-id");for(const e of o)e.remove()}}const Ns=new Set(["for","if","elseif","else"]);function vs(e){const t=new vn;if(0===e.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:t};const n=e[0].parentNode,o=e[e.length-1].nextSibling,s=document.createElement("div");for(const t of e)s.appendChild(t);const[r,i]=ve(s),a=t.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:t}}function Ss(e,t,o){const s={for:n.commentForPrefix,if:n.commentIfPrefix,elseif:n.commentElseIfPrefix,else:n.commentElsePrefix}[t];if(!s)return null;const r=`@@${s}:${o}`,i=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const e=i.currentNode;if(e.data===r)return e}return null}function xs(e,t){const o=e;let s=null;for(const[e,r]of t.templates){let t=le(r.getAttribute(n.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&s?t={...s,outFilters:[...s.outFilters,Ko()],bindingType:"else"}:"elseif"===i&&s&&(t={...t,stateName:s.stateName}),"if"===i||"elseif"===i?s=t:"else"===i&&(s=null);const a=document.importNode(r.content,!0),c="for"===i?t.statePathName:void 0;ss(a),"string"==typeof c&&ts(a,c),ls(o,a,c);me(e,o,{fragment:a,parseBindTextResult:t,nodeInfos:os(a)})}}async function Is(e){await ds(e);const t=e.querySelectorAll(n.tagNames.ssr);for(const n of t){const t=n;if(!t.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${t.version}", client="${fs}". Falling back to full render.`),ws.cleanupDom(e),!1}for(const n of t)xs(e,n);const o=function(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const e of o){const n=ms.exec(e.data);if(!n)continue;const o=n[1],s=n[2],r=s.split(":");let i,a,c=null;"for"===o?(i=r[0],a=r[1],c=parseInt(r[2],10)):(i=r[0],a=r.slice(1).join(":"));const l=[];let d=e.nextSibling;const u=`@@wcs-${o}-end:${s}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)l.push(d),d=d.nextSibling;t.push({type:o,uuid:i,path:a,index:c,nodes:l})}return t}(document.body);!function(e,t){const n=new Map;for(const o of t){if(0===o.nodes.length)continue;const t=lo(o.nodes),{bindingInfos:s,subscriberNodes:r,bindingSession:i}=vs(o.nodes);Yn(t,i);for(const e of r)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");Gn(t,s),Zn(t,r);const a=[];for(const e of s)e.statePathName in p&&a.push(e);if(Cn(t,a),"for"===o.type&&null!==o.index){const r=Ss(e,"for",o.uuid);if(r){const e=Rn(null,o.index);go(r,e,t),bo(r,o.nodes[o.nodes.length-1]),ro(r,t),eo(t,ct(T(o.path+"."+l),e)),i.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});let a=n.get(o.uuid);a||(a=[],n.set(o.uuid,a)),a.push(e)}}else{const n=Ss(e,o.type,o.uuid);n&&(ro(n,t),i.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}))}}for(const[t,o]of n){const n=Ss(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=ge(t);if(!r)continue;const i=r.parseBindTextResult.stateName,a=r.parseBindTextResult.statePathName,c=$s(s,i);c&&c.createState("readonly",e=>{const t=e[a];Array.isArray(t)&&Bn(t,o)})}}(document.body,o),ws.removeBlockBoundaryComments(document.body);const s=[];for(const e of t)e.parentNode&&(s.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());ws.restoreTextBindings(document.body);const[r,i]=ve(document.body);for(const e of r)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||(Ae(e,null),t.setAttribute("data-wcs-completed",""))}else Ae(e,null);const a=[],c=[],d=Sn(document.body).initialize(i);for(const e of d)if("event"!==e.bindingType)if(Ns.has(e.bindingType))c.push(e);else{if(e.statePathName.includes(l))continue;a.push(e)}for(const e of c)if("for"===e.bindingType){const t=Qe(e),n=$s(e.replaceNode.getRootNode(),e.stateName);n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&$e(t,o)})}zo(a);for(const{el:e,parent:t,next:n}of s)t.insertBefore(e,n);const u=e.querySelectorAll(n.tagNames.ssr);for(const t of u){const n=t.hydrateProps;for(const[t,o]of Object.entries(n)){const n=e.querySelector(`[data-wcs-ssr-id="${t}"]`);if(n)for(const[e,t]of Object.entries(o))n[e]=t}}const f=e.querySelectorAll("[data-wcs-completed]");for(const e of f)e.removeAttribute("data-wcs-completed");return!0}const As=new WeakMap,_s=new WeakMap,Ps=new Set;function $s(e,t){let n=As.get(e);return n&&n.get(t)||null}function Ts(e){return _s.get(e)??Promise.resolve()}function ks(t,o,s){let r=As.get(t);if(null===s){if(!r)return;const e=r.get(o);r.delete(o),0===r.size&&As.delete(t),void 0!==e&&(Ps.delete(e),null!==et&&et({type:"state:element-unregistered",name:o,rootNode:t,element:e})),n.debug&&console.debug(`State element unregistered: name="${o}"`)}else{if(!r){r=new Map,As.set(t,r);const n=!e()&&s.hasAttribute?.("enable-ssr");if("HTMLDocument"===t.constructor.name||"Document"===t.constructor.name){const e=new Promise(e=>{queueMicrotask(async()=>{if(n){await Is(t)||await us(t)}else await us(t);e()})});_s.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise(e=>{queueMicrotask(async()=>{await us(t),e()})});_s.set(t,e)}}r.has(o)&&j(`State element with name "${o}" is already registered.`),r.set(o,s),Ps.add(s),null!==et&&et({type:"state:element-registered",name:o,rootNode:t,element:s}),n.debug&&console.debug(`State element registered: name="${o}"`,s)}}const Cs=new Set;function Es(e){Cs.add(e)}const Ms=new class{_queueUpdateRecords=[];constructor(){}enqueueAbsoluteAddress(e,t=null){const n=0===this._queueUpdateRecords.length;this._queueUpdateRecords.push({absoluteAddress:e,context:t}),n&&queueMicrotask(()=>{const e=this._queueUpdateRecords;this._queueUpdateRecords=[],this._applyChange(e)})}testApplyChange(e,t){this._applyChange(e.map((e,n)=>({absoluteAddress:e,context:t?.[n]??null})))}_applyChange(e){const t=new Map;for(const n of e){const e=t.get(n.absoluteAddress);null!==et&&null!=e&&null!==n.context&&e.transactionId!==n.context.transactionId&&et({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:e.transactionId,winnerTransactionId:n.context.transactionId}),t.set(n.absoluteAddress,n.context)}const n=[],o=new Map;for(const[e,s]of t){if(null!==s&&s.hop>=32){console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:e.absolutePathInfo.pathInfo.path,stateName:e.absolutePathInfo.stateName,transactionId:s.transactionId,hop:s.hop,maxHops:32}),null!==et&&et({type:"propagation:hop-limit",absoluteAddress:e,transactionId:s.transactionId,hop:s.hop});continue}const t=nt(e);if(void 0!==t)for(const e of t)!1!==e.replaceNode.isConnected&&(n.push(e),null!==s&&o.set(e,s))}o.size>0?zo(n,o):zo(n),function(e){for(const t of Cs)t(e)}(new Set(t.keys()))}};function Os(){return Ms}const Ds="__WCSTACK_DEVTOOLS_HOOK__";function Rs(){const e=globalThis,t=e[Ds];if(void 0!==t)return 1!==t.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${t.version}, expected 1. Keeping the existing registry (first-wins).`),t;const n=function(){const e=new Map,t=new Set,n=e=>{if(0===t.size)return void e._setSink(null);const n=e.id;e._setSink(e=>{for(const o of t)o.onEvent?.(n,e)})};return{version:1,sources:e,register(o){if(!e.has(o.id)){e.set(o.id,o),n(o);for(const e of t)e.onSourceRegistered?.(o)}},unregister(n){const o=e.get(n);if(void 0!==o){o._setSink(null),e.delete(n);for(const e of t)e.onSourceUnregistered?.(n)}},addListener(o){t.add(o);for(const t of e.values())n(t),o.onSourceRegistered?.(t);return()=>{if(t.delete(o))for(const t of e.values())n(t)}}}}();return e[Ds]=n,n}const Ls=e=>{null!==et&&et({type:"state:update-batch",addresses:e})};function Ws(e){const t=null!==et;!function(e){et=e}(e);const n=null!==e;var o;n&&!t?Es(Ls):!n&&t&&(o=Ls,Cs.delete(o))}function Bs(e){return{name:e.name,rootNode:e.rootNode,element:e,paths:{list:e.listPaths,element:e.elementPaths,getter:e.getterPaths,setter:e.setterPaths},commandTokenNames:e.commandTokenNames,eventTokenNames:e.eventTokenNames,staticDependency:e.staticDependency,dynamicDependency:e.dynamicDependency}}function js(e,t){return $s(t,e)??j(`devtools: state element not found: name="${e}"`)}let Fs=null;function zs(){if(e())return;if(null!==Fs)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:fs,getStateElements(){const e=[];for(const t of Ps)e.push(Bs(t));return e},keys(e,t){const n=js(e,t),o=[];return n.createState("readonly",e=>{for(const t of Object.keys(e))if(!t.includes("*")&&!t.startsWith("$")){try{if("function"==typeof e[t])continue}catch{}o.push(t)}}),o},read(e,t,n,o){let s;return js(e,t).createState("readonly",e=>{s=e.$resolve(n,o??[])}),s},write(e,t,n,o,s){js(e,t).createState("writable",e=>{void 0!==s&&s.length>0?e.$resolve(n,s,o):e[n]=o})},_setSink:Ws};Fs=t,Rs().register(t)}async function qs(e,t){let n=null;const o=`\n//# sourceURL=${t}\n`;if("function"==typeof URL.createObjectURL){const t=new Blob([e.text+o],{type:"application/javascript"}),s=URL.createObjectURL(t);try{n=await import(s)}finally{URL.revokeObjectURL(s)}}else{const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(e.text+o)));n=await import(`data:application/javascript;base64,${t}`)}return n&&"object"==typeof n.default?n.default:{}}async function Us(e){try{return(await import(e)).default||{}}catch(e){j(`Failed to load script file: ${e}`)}}class Vs{_loopContextStack=Array(d).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&j("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=d&&j("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&&j("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const e=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==e&&j("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else n.listIndex.length!==n.pathInfo.wildcardCount&&j(`Cannot push loop context when there is no active loop context: the list index chain (length ${n.listIndex.length}) does not cover the wildcard path (wildcard count ${n.pathInfo.wildcardCount}).`);let s;this._loopContextStack[this._length]=n,this._length++;try{s=t(n)}finally{s instanceof Promise?s.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return s}}const Hs=new WeakMap;function Gs(e,t){let n=Hs.get(e);void 0===n&&(n=new Map,Hs.set(e,n));let o=n.get(t);return void 0===o&&(o=new At(t,e.name),n.set(t,o)),o}const Js=new WeakMap;function Ks(e){const t=Js.get(e);if(void 0!==t)return t;const n=new Proxy(Object.create(null),{get(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return Gs(e,n)},has:(t,n)=>"string"==typeof n&&e.commandTokenNames.has(n),ownKeys:()=>Array.from(e.commandTokenNames),getOwnPropertyDescriptor(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:Gs(e,n)}},set(){j("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){j("$command namespace is read-only; deleting from it is not allowed.")}});return Js.set(e,n),n}const Ys=Symbol("wcs-stream-last-notified-uncertain"),Xs=new WeakMap;function Qs(e,t){const n=Xs.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function Zs(e,t){const n=Xs.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:Ys,error:Object.is(o.error,null)?null:Ys})}const er=new Set;function tr(e){er.delete(e)}function nr(){return er}const or=new WeakMap;function sr(e){return or.get(e)??new Map}function rr(e){tr(e);const t=or.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Zs(e,n.name)}const ir=(e,t)=>t,ar=new Set;function cr(e,t){const n=t[x];if(void 0===n)return void Qs(e,ar);"object"==typeof n&&null!==n||j(`${x} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[s,r]of Object.entries(n)){0===s.length&&j(`${x} entry name must be a non-empty string.`),s.includes(c)&&j(`${x} entry "${s}" must be a flat property name ("${c}" is not allowed).`),s.includes(l)&&j(`${x} entry "${s}" must be a flat property name ("${l}" is not allowed).`),s.startsWith("$")&&j(`${x} entry "${s}" must not start with "$" (reserved namespace).`),s in Object.prototype&&j(`${x} entry "${s}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(s)&&j(`${x} entry "${s}" conflicts with a getter declared on the state.`),e.setterPaths.has(s)&&j(`${x} entry "${s}" conflicts with a setter declared on the state.`),"object"==typeof r&&null!==r||j(`${x} entry "${s}" must be an object ({ args?, source, fold?, initial? }).`);const n=r;"function"!=typeof n.source&&j(`${x} entry "${s}" source must be a function.`);const i=void 0!==n.fold;i&&"function"!=typeof n.fold&&j(`${x} entry "${s}" fold must be a function.`),i&&!("initial"in n)&&j(`${x} entry "${s}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&j(`${x} entry "${s}" args must be a function.`);const a={name:s,definition:{args:n.args??null,source:n.source,fold:n.fold??ir,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};s in t||(t[s]=a.definition.initial),o.set(s,a)}!function(e,t){or.set(e,t)}(e,o),Qs(e,new Set(o.keys()))}const lr=new WeakMap,dr=new WeakMap;function ur(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=sr(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&sr(e).has(n),ownKeys:()=>Array.from(sr(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=sr(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){j(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){j(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function fr(e){const t=lr.get(e);if(void 0!==t)return t;const n=ur(e,I,e=>e.status);return lr.set(e,n),n}function pr(e){const t=dr.get(e);if(void 0!==t)return t;const n=ur(e,A,e=>e.error);return dr.set(e,n),n}function hr(e){lr.delete(e),dr.delete(e)}let mr=null;async function gr(e,t,n,o){let s=null,r=null;const i=()=>{if(s&&s!==r){r=s;try{s.return?.()?.then?.(void 0,()=>{})}catch{}}};n.addEventListener("abort",i,{once:!0});try{const r=await e(t,n);if(s=function(e,t){if("function"==typeof e?.[Symbol.asyncIterator])return e;if("function"!=typeof e?.getReader)throw new TypeError("[@wcstack/state] $streams: source must return an AsyncIterable or a ReadableStream (got neither).");return async function*(e,t){const n=e.getReader(),o=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",o,{once:!0});try{for(;;){const{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t.removeEventListener("abort",o),n.releaseLock()}}(e,t)}(r,n)[Symbol.asyncIterator](),n.aborted)return void i();for(;;){const e=await s.next();if(e.done)break;if(n.aborted)return;o.fold(e.value)}if(n.aborted)return;o.done()}catch(e){if(n.aborted)return;o.fail(e)}finally{n.removeEventListener("abort",i)}}function br(e){const t=sr(e);if(0!==t.size){!function(e){er.add(e)}(e);for(const n of t.values())yr(e,n)}}function yr(e,t){t.controller?.abort();const n=new AbortController;t.controller=n;const o=function(e,t){const n=t.definition.args;if(null===n)return void t.depAddresses.clear();const o=mr,s=new Set;let r;mr=s;try{e.createState("readonly",e=>{r=n(e)})}finally{mr=o}r instanceof Promise&&j(`${x} entry "${t.name}" args must be synchronous (it returned a Promise).`);const i=`${I}${c}${t.name}`,a=`${A}${c}${t.name}`;for(const n of s){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==e||o.path!==t.name&&o.path!==i&&o.path!==a||j(`${x} entry "${t.name}" args must not read the stream itself ("${o.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),o.wildcardCount>0&&j(`${x} entry "${t.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return t.depAddresses=s,r}(e,t);e.createState("writable",e=>{e[t.name]=t.definition.initial}),wr(e,t,"active",null);const s=t.definition,r={fold(n){e.createState("writable",e=>{e[t.name]=s.fold(e[t.name],n)})},done(){wr(e,t,"done",null)},fail(o){wr(e,t,"error",o),n.abort()}};gr(s.source,o,n.signal,r)}function wr(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return Xs.get(e)?.get(t)??{status:"idle",error:null}}(e,t.name),r=s.status!==n,i=!Object.is(s.error,o);(r||i)&&(!function(e,t,n,o){let s=Xs.get(e);void 0===s&&(s=new Map,Xs.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{r&&e.$postUpdate(`${I}${c}${t.name}`),i&&e.$postUpdate(`${A}${c}${t.name}`)}))}function Nr(e){return function(){const t=this.stateElement;if(!t)return;let n;try{t.createState("readonly",t=>{n=t[e]})}catch(t){return void console.warn(`[@wcstack/state] DCC getter "${e}" failed:`,t)}return n}}function vr(e){return function(t){const n=this.stateElement;n&&n.initializePromise.then(()=>{n.createState("writable",n=>{n[e]=t})})}}function Sr(e,t){return t?function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[e](...t)}).then(()=>o)})}:function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[e](...t)}),o})}}function xr(e){return e.startsWith("$")}Es(function(e){const t=nr();if(0===t.size)return;const n=[];for(const o of t)for(const t of sr(o).values())for(const s of t.depAddresses)if(e.has(s)){n.push({stateElement:o,entry:t});break}for(const{stateElement:e,entry:o}of n)if(t.has(e)&&sr(e).get(o.name)===o)try{yr(e,o)}catch(n){o.controller?.abort(),t.has(e)&&sr(e).get(o.name)===o&&wr(e,o,"error",n)}});const Ir=new Map;class Ar{path;segments;paths;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(e){const t=e.split("."),n=t.slice(),o=[];let s=0,r=0,i="",a=0,c="none";const l=[];for(let e=0;e<t.length;e++){const c=t[e];if("*"===c)n[e]="*",l.push(null),s++,a++;else{const t=Number(c);Number.isNaN(t)||(n[e]="*",l.push(t),r++,a++)}i+=c,o.push(i),i+=e<c.length-1?".":""}const d=T(n.join("."));(s>0||r>0)&&(c=s===a?"context":r===a?"all":"partial"),this.path=e,this.segments=t,this.paths=o,this.wildcardCount=a,this.wildcardType=c,this.wildcardIndexes=l,this.pathInfo=d}}function _r(e){let t;return Ir.get(e)??(Ir.set(e,t=new Ar(e)),t)}const Pr=new WeakMap;function $r(e,t){null===t?Pr.delete(e):Pr.set(e,t)}function Tr(e){const t=Pr.get(e);t&&(t.dirty=!0)}function kr(e,t){let n=e;for(let e=1;e<t.length;e++){if(Object(n)!==n)return;n=Reflect.get(n,t[e])}return n}function Cr(e,t,n,o,s){const r=t.pathInfo.segments[0];if(r===N)return kr(Ks(s),t.pathInfo.segments);if(r===I)return kr(fr(s),t.pathInfo.segments);if(r===A)return kr(pr(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){const s=Mr(e,t.parentAddress??j(`address.parentAddress is undefined path: ${t.pathInfo.path}`),n,o),r=t.pathInfo.segments[t.pathInfo.segments.length-1];if(r===l){const e=t.listIndex?.index??j(`address.listIndex?.index is undefined path: ${t.pathInfo.path}`);return Reflect.get(s,e)}return Reflect.get(s,r)}if(!s.getterPaths.has(t.pathInfo.path))return Reflect.get(e,t.pathInfo.path);o.pushAddress(t);try{return Reflect.get(e,t.pathInfo.path,n)}finally{o.popAddress()}}function Er(e,t,n,o,s){const r=qe(We(s,t.pathInfo),t.listIndex),i=function(e){return Pr.get(e)??null}(r);if(null!==i&&!1===i.dirty)return i.value;const a=Cr(e,t,n,o,s);return $r(r,{value:a,dirty:!1}),a}function Mr(e,t,n,o){!function(e,t){if(e.addressStackLength>0){const n=e.lastAddressStack,o=n?.pathInfo??null,s=e.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==t.pathInfo.path&&(s.addDynamicDependency(t.pathInfo.path,o.path),t.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const e=Je(t.pathInfo,o);if(e>0){let o=!1;for(let s=0;s<e;s++)if(t.listIndex?.at(s)!==n.listIndex?.at(s)){o=!0;break}if(o)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}(o,t),function(e,t){if(null===mr)return;const n=We(e,t.pathInfo);mr.add(qe(n,t.listIndex))}(o.stateElement,t);const s=o.stateElement;return t.pathInfo.wildcardCount>0||s.getterPaths.has(t.pathInfo.path)?Er(e,t,n,o,s):Cr(e,t,n,o,s)}function Or(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[t];return void 0===o?null:n.listIndex?.at(o)??null}function Dr(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=Mr(e,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=t.pathInfo.lastSegment;if(i===l){const e=t.listIndex?.index;return"number"==typeof e&&e in r}return i in r}const Rr=new WeakMap;function Lr(e,t){null===t?Rr.delete(e):Rr.set(e,t)}function Wr(e,t,o){const s=T(e.wildcardParentPaths[t]),r=We(e.stateElement,s),i=ct(s,o),a=Pe(qe(r,o)),c=e.stateProxy[Ce](i),l=function(e,t){switch(t){case"old":return e.oldIndexes;case"new":return e.newIndexes;case"add":return e.addIndexSet;case"change":return e.changeIndexSet;case"delete":return e.deleteIndexSet;default:return n.debug&&console.log(`Invalid search type: ${t}`),[]}}(qn(i.listIndex,a,c),e.searchType);if(t===e.wildcardPaths.length-1)e.targetListIndexes.push(...l);else for(const n of l)Wr(e,t+1,n)}function Br(e,t,n,o,s){return"full"===e.listExpansion||e.stateElement.crossRowListPaths?.has(t)?s.newIndexes:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?s.newIndexes:s.changeIndexSet:0===s.addIndexSet.size?s.changeIndexSet:0===s.changeIndexSet.size?s.addIndexSet:[...s.addIndexSet,...s.changeIndexSet]}function jr(e,t,n,o,s,r,i,a,c,d){const u={stateElement:t,staticMap:o,dynamicMap:s,result:new Set,listPathSet:r,visited:new Set,stateProxy:i,searchType:a,listExpansion:d?.listExpansion??"full"};return function(e,t,n){const o=[{address:t,depth:0}];for(;o.length>0;){const{address:t,depth:s}=o.pop();if(s>1e3&&j(`Maximum dependency depth of 1000 exceeded. Possible circular dependency detected at path: ${t.pathInfo.path}`),e.visited.has(t))continue;e.visited.add(t),n(t);const r=t.pathInfo.path,i=s+1,a=[],c=e.staticMap.get(r);if(c)for(const n of c){const o=T(n);if(e.listPathSet.has(r)&&o.lastSegment===l){const n=e.stateProxy[Ce](t),s=Pe(qe(We(e.stateElement,t.pathInfo),t.listIndex)),c=qn(t.listIndex,s,n);for(const t of Br(e,r,0,0,c)){const n=ct(o,t);e.result.add(n),a.push({address:n,depth:i})}}else{const n=ct(o,t.listIndex);e.result.add(n),a.push({address:n,depth:i})}}const d=e.dynamicMap.get(r);if(d)for(const n of d){const o=T(n),s=[];if(o.wildcardCount>0){const n=Je(t.pathInfo,o);if(o.wildcardCount-n>=1){let r;n>0?(null===t.listIndex&&j(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),r=t.listIndex.at(n-1)):r=null;const i={stateElement:e.stateElement,targetListIndexes:[],wildcardPaths:o.wildcardPaths,wildcardParentPaths:o.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};Wr(i,n,r),s.push(...i.targetListIndexes)}else{null===t.listIndex&&j(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=t.listIndex.at(n-1);s.push(e)}}else s.push(null);for(const t of s){const n=ct(o,t);e.result.add(n),a.push({address:n,depth:i})}}for(let e=a.length-1;e>=0;e--)o.push(a[e])}}(u,n,c),Array.from(u.result)}function Fr(e,t,o,s,r,i){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,s);const o=Mr(e,n,r,i),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===l){const e=t.listIndex?.index??j(`address.listIndex?.index is undefined path: ${t.pathInfo.path}`);return Reflect.set(o,e,s)}return Reflect.set(o,a,s)}if(!i.stateElement.setterPaths.has(t.pathInfo.path))return Reflect.set(e,t.pathInfo.path,s);i.pushAddress(t);try{return Reflect.set(e,t.pathInfo.path,s,r)}finally{i.popAddress()}}finally{const e=n.enablePropagationContext?Kt()??Ht(-1):null,s=Os();s.enqueueAbsoluteAddress(o,e),jr(i.stateName,i.stateElement,t,i.stateElement.staticDependency,i.stateElement.dynamicDependency,i.stateElement.listPaths,r,"new",n=>{if(n===t)return;const o=qe(We(i.stateElement,n.pathInfo),n.listIndex);Tr(o),s.enqueueAbsoluteAddress(o,e)},{listExpansion:"diff"})}}function zr(e,t,n,o,s,r){let i=t.parentAddress??j(`address.parentAddress is undefined path: ${t.pathInfo.path}`),a=function(e){return Rr.get(e)??null}(i);if(null===a){const t=Mr(e,i,s,r)??[],n=Wn(t)??[];a={value:[...t],listIndexes:[...n]},Lr(i,a)}try{return Fr(e,t,n,o,s,r)}finally{const n=a.value.indexOf(o),c=Mr(e,i,s,r)??[],l=Array.isArray(c)?Wn(c)??[]:[],d=t.listIndex.index,u=-1!==n?a.listIndexes[n]:Rn(i.listIndex,-1);l[d]=u;if(new Set(c).size===a.value.length){for(let e=0;e<l.length;e++)l[e].index=e;Lr(i,null)}}}function qr(e,t,o,s,r){const i=r.stateElement;let a,c=!1;if(n.sameValueGuard&&(null===o||"object"!=typeof o)){const n=Mr(e,t,s,r);if(Dr(e,t,s,r)&&Object.is(n,o))return!0;a=n,c=!0}const l=i.elementPaths.has(t.pathInfo.path),d=t.pathInfo.wildcardCount>0||i.getterPaths.has(t.pathInfo.path),u=qe(We(i,t.pathInfo),t.listIndex);null!==et&&et({type:"state:write",absoluteAddress:u,value:o,oldValue:a,hasOldValue:c});try{return l?zr(e,t,u,o,s,r):Fr(e,t,u,o,s,r)}finally{d&&$r(u,{value:o,dirty:!1});const e=i.bindableEventMap[t.pathInfo.path];if(e){const t=i.rootNode;t instanceof ShadowRoot&&t.host.dispatchEvent(new CustomEvent(e,{detail:o,bubbles:!0}))}}}function Ur(e,t,n,o){return(t,s,r)=>{const i=T(t);if(o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}i.wildcardParentPathInfos.length>s.length&&j(`indexes length is insufficient: ${t}`);let a=null;for(let t=0;t<i.wildcardParentPathInfos.length;t++){const r=i.wildcardParentPathInfos[t],c=ct(r,a),l=Wn(Mr(e,c,n,o));null==l&&j(`ListIndexes not found: ${r.path}`);a=l[s[t]]??j(`ListIndex not found: ${r.path}`)}const c=ct(i,a);if(!(void 0!==r))return Mr(e,c,n,o);qr(e,c,r,n,o)}}const Vr=new WeakMap;function Hr(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return Or(o,s.wildcardPaths.at(-1)??j(`lastWildcardPath is null: ${t.pathInfo.path}`))??j(`ListIndex not found: ${t.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<t.pathInfo.wildcardCount;r++){const i=t.pathInfo.wildcardParentPathInfos[r]??j(`wildcardParentPathInfo is null: ${t.pathInfo.path}`);s=(Wn(Mr(e,ct(i,s),n,o))??j(`ListIndex not found: ${i.path}`))[t.wildcardIndexes[r]??j(`wildcardIndex is null: ${t.pathInfo.path}`)]??j(`ListIndex not found: ${i.path}`)}return s}case"partial":j(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function Gr(e,t,n){void 0!==e.loopContext&&j("already in loop context"),e.setLoopContext(t);try{e.pushAddress(t);try{return n()}finally{e.popAddress()}}finally{e.clearLoopContext()}}const Jr=`${I}${c}`,Kr=`${A}${c}`;function Yr(e,t,n,o){const s=p[t];if(void 0!==s){0===o.addressStackLength&&j(`No active state reference to get list index for "${t.toString()}".`);const e=o.lastAddressStack?.listIndex;return e?.indexes[s]??j(`ListIndex not found: ${t.toString()}`)}if("string"==typeof t){if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>function(e,t,n,o){const s=Ur(e,0,n,o);return(t,r)=>{const i=new Map,a=T(t);if(o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==a.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(a.path,e.path)}if(void 0===r){for(let e=0;e<a.wildcardParentPathInfos.length;e++){const t=a.wildcardParentPathInfos[e],n=Or(o,t.path);if(n){r=n.indexes;break}}void 0===r&&(r=[])}const c=(t,s,r,a,l,d,u)=>{const f=t[s]??null;if(null===f)return void u.push(d);const p=ct(f,r),h=Vr.get(p),m=Mr(e,p,n,o),g=qn(r,h,m).newIndexes,b=a[l]??null;if(i.set(p,m),null===b)for(let e=0;e<g.length;e++){const n=g[e];c(t,s+1,n,a,l+1,d.concat(n.index),u)}else{const e=g[b]??j(`ListIndex not found: ${f.path}`);s+1<t.length?c(t,s+1,e,a,l+1,d.concat(e.index),u):u.push(d.concat(e.index))}},l=[];c(a.wildcardParentPathInfos,0,null,r,0,[],l);const d=[];for(let e=0;e<l.length;e++)d.push(s(a.path,l[e]));for(const[e,t]of i.entries())Vr.set(e,t);return d}}(e,0,n,o)(t,s);case"$postUpdate":return t=>function(e,t,n,o){const s=o.stateElement;return t=>{const r=_r(t),i=Hr(e,r,n,o),a=ct(r.pathInfo,i),c=qe(We(s,a.pathInfo),a.listIndex),l=Os();l.enqueueAbsoluteAddress(c),jr(o.stateName,o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=qe(We(s,e.pathInfo),e.listIndex);Tr(t),l.enqueueAbsoluteAddress(t)})}}(e,0,n,o)(t);case"$resolve":return(t,s,r)=>Ur(e,0,n,o)(t,s,r);case"$trackDependency":return e=>function(e,t,n,o){return e=>{0===o.addressStackLength&&j(`No active state reference to track dependency for path "${e}".`);const t=o.lastAddressStack?.pathInfo??j("Internal error: lastAddressStack is null"),n=o.stateElement;o.stateElement.getterPaths.has(t.path)&&t.path!==e&&n.addDynamicDependency(e,t.path)}}(0,0,0,o)(e);case N:return Ks(o.stateElement);case I:return fr(o.stateElement);case A:return pr(o.stateElement)}if(!t.startsWith(Jr)&&!t.startsWith(Kr))return}const s=_r(t),r=Hr(e,s,n,o),i=ct(s.pathInfo,r);return Mr(e,i,n,o)}if("symbol"==typeof t){switch(t){case Te:return(e,t=async()=>{})=>async function(e,t,n){return await Gr(e,t,n)}(o,e,t);case ke:return(e,t=()=>{})=>function(e,t,n){return Gr(e,t,n)}(o,e,t);case Ce:return t=>Mr(e,t,n,o);case Ee:return t=>Dr(e,t,n,o);case Me:return(t,s)=>qr(e,t,s,n,o);case Oe:return()=>async function(e,t,n){const o=Reflect.get(e,h);"function"==typeof o&&await o.call(n)}(e,0,n);case De:return()=>function(e,t,n){const o=Reflect.get(e,m);"function"==typeof o&&o.call(n)}(e,0,n);case Re:return t=>function(e,t,n,o){const s=Reflect.get(e,g);if("function"==typeof s){const e=new Set,r={};for(const n of t){const t=n.absolutePathInfo.pathInfo;let s;if(s=n.absolutePathInfo.stateName===o.stateName?t.path:t.path+"@"+n.absolutePathInfo.stateName,e.add(s),t.wildcardCount>0){const e=n.listIndex.indexes??[],t=r[s];void 0===t?r[s]=[e]:t.push(e)}}return s.call(n,Array.from(e),r)}}(e,t,n,o)}return Reflect.get(e,t,n)}}class Xr{_stateElement;_stateName;_addressStack=Array(d).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;constructor(e,t,n){this._stateName=t;const o=$s(e,this._stateName);null===o&&j(`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 e;return this._addressStackIndex>=0&&(e=this._addressStack[this._addressStackIndex]),void 0===e&&j("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex++,this._addressStackIndex>=d&&j("Exceeded maximum address stack depth of 128. Possible infinite loop."),this._addressStack[this._addressStackIndex]=e}popAddress(){if(this._addressStackIndex<0)return null;const e=this._addressStack[this._addressStackIndex];return void 0===e&&j(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,e}setLoopContext(e){this._loopContext=e}clearLoopContext(){this._loopContext=void 0}get(e,t,n){return Yr(e,t,n,this)}set(e,t,n,o){return"readonly"===this._mutability&&j(`State "${this._stateName}" is readonly.`),function(e,t,n,o,s){if("string"==typeof t){const r=_r(t),i=Hr(e,r,o,s);return qr(e,ct(r.pathInfo,i),n,o,s)}return Reflect.set(e,t,n,o)}(e,t,n,o,this)}has(e,t){return Reflect.has(e,t)}}const Qr=new WeakMap;const Zr=new WeakMap;function ei(e,t){const n=Zr.get(e);return n?n.get(t)??null:null}const ti=new WeakMap,ni=new WeakMap,oi=new WeakMap,si=new WeakMap;function ri(e,t){return{innerAbsPathInfo:We(e,T(t.propSegments.slice(1).join(c))),outerAbsPathInfo:Qe(t).absolutePathInfo}}function ii(e,t){let n=ti.get(e);if(void 0===n&&(n=new Map,ti.set(e,n)),n.has(t))return n.get(t);let o=ni.get(e);void 0===o&&(o=new Map,ni.set(e,o));const s=oi.get(e);if(void 0===s)return null;let r=null;for(const e of s)if(t.pathInfo.cumulativePathInfoSet.has(e.innerAbsPathInfo.pathInfo)){e.innerAbsPathInfo.pathInfo.segments.length===t.pathInfo.segments.length&&j("Duplicate mapping rule for web component."),r=e;break}if(null===r)return null;const i=si.get(r);void 0===i&&j("Binding not found for primary mapping rule on web component.");const a=t.pathInfo.segments.slice(r.innerAbsPathInfo.pathInfo.segments.length),l=T(r.outerAbsPathInfo.pathInfo.segments.concat(a).join(c)),d=$s(e.getRootNode(),i.stateName);null===d&&j(`State element with name "${i.stateName}" not found for web component.`);const u=We(d,l);n.set(t,u),o.set(u,t);return function(e,t){const n=V(e);null===n?H(e,[t]):n.push(t)}(e,{...i,propName:t.pathInfo.path,propSegments:t.pathInfo.segments,statePathName:u.pathInfo.path,statePathInfo:u.pathInfo}),u}function ai(e){return function(e){const t=Object.getPrototypeOf(e),n=Object.create(t),o=Object.getOwnPropertyDescriptors(e);for(const e in o){const t=o[e];!1===t.writable&&(t.writable=!0)}return Object.defineProperties(n,o),n}(e)}class ci{_webComponent;_innerStateElement;constructor(e,t){this._webComponent=e,this._innerStateElement=ei(e,t)??j("State element not found for web component.")}get(e,t,n){if("string"!=typeof t)return Reflect.get(e,t,n);{if("then"===t)return;if("$"===t[0])return;if(this._innerStateElement.getterPaths.has(t)&&t in e)return Reflect.get(e,t,n);const o=T(t),s=We(this._innerStateElement,o),r=ii(this._webComponent,s);if(null!==r){const e=Ie(this._webComponent);let t;return r.stateElement.createState("readonly",n=>{n[ke](e,()=>{t=n[r.pathInfo.path];let o=null;null!==e&&null!==e.listIndex&&r.pathInfo.wildcardCount>0&&(o=e.listIndex.at(r.pathInfo.wildcardCount-1));!function(e,t){Qr.set(e,t)}(qe(r,o),t)})}),t}if(t in e)return Reflect.get(e,t,n);j(`Property "${t}" not found in inner state: no mapping rule and no local state property.`)}}set(e,t,n,o){if("string"!=typeof t)return Reflect.set(e,t,n,o);{if(this._innerStateElement.setterPaths.has(t)&&t in e)return Reflect.set(e,t,n,o);const s=T(t),r=We(this._innerStateElement,s),i=ii(this._webComponent,r);if(null!==i){const e=Ie(this._webComponent);return i.stateElement.createState("writable",t=>{t[ke](e,()=>{t[i.pathInfo.path]=n})}),!0}if(t in e)return Reflect.set(e,t,n,o);j(`Property "${t}" not found in inner state: no mapping rule and no local state property.`)}}has(e,t){if("string"==typeof t){if("$"===t[0])return!1;if((this._innerStateElement.getterPaths.has(t)||this._innerStateElement.setterPaths.has(t))&&t in e)return!0;const n=T(t),o=We(this._innerStateElement,n);return null!==ii(this._webComponent,o)||t in e}return Reflect.has(e,t)}}class li{_innerStateElement;constructor(e,t){this._innerStateElement=ei(e,t)??j("State element not found for web component.")}get(e,t,n){if("string"==typeof t){const e=T(t),n=qe(We(this._innerStateElement,e),null);return o=n,Qr.get(o)}return Reflect.get(e,t,n);var o}set(e,t,n,o){if("string"==typeof t){const e=T(t),n=We(this._innerStateElement,e);return this._innerStateElement.createState("readonly",e=>{e.$postUpdate(n.pathInfo.path)}),!0}return Reflect.set(e,t,n,o)}}class di{_innerStateElement;constructor(e,t){this._innerStateElement=ei(e,t)??j("State element not found for web component.")}get(e,t,n){if("string"==typeof t){let e;return this._innerStateElement.createState("readonly",n=>{e=n[t]}),e}return Reflect.get(e,t,n)}set(e,t,n,o){return"string"==typeof t?(this._innerStateElement.createState("writable",e=>{e[t]=n}),!0):Reflect.set(e,t,n,o)}}const ui=e=>()=>e;function fi(e,t,o,s){if(function(e,t,n){let o=Zr.get(e);o||(o=new Map,Zr.set(e,o)),o.set(t,n)}(t,o,e),t.hasAttribute(n.bindAttributeName)){const n=(V(t)??[]).filter(e=>e.propSegments[0]===o);!function(e,t,n){if(0===n.length)return;const o=ei(e,t);null===o&&j("State element not found for web component.");const s=new Map,r=new Map;for(const t of n){const n=ri(o,t);let i=oi.get(e);void 0===i?oi.set(e,new Set([n])):i.add(n);const a=n.innerAbsPathInfo,c=n.outerAbsPathInfo;si.set(n,t),s.set(a,c),r.set(c,a)}ti.set(e,s),ni.set(e,r)}(t,o,n);const s=function(e,t){const n=new li(e,t);return new Proxy({},n)}(t,o),r=function(e,t){const n=new ci(e,t),o=ei(e,t);null===o&&j("State element not found for web component."),null===o.boundComponentStateProp&&j("State element is not bound to any component state prop."),o.boundComponentStateProp in e||j(`State element is not bound to a valid component state prop: ${o.boundComponentStateProp}`);const s=e[o.boundComponentStateProp];return"object"==typeof s&&null!==s||j(`Invalid state object for component state prop: ${o.boundComponentStateProp}`),new Proxy(ai(s),n)}(t,o);e.setInitialState(r),Object.defineProperty(t,o,{get:ui(s),enumerable:!0,configurable:!0})}else{e.setInitialState(ai(s));const n=function(e,t){const n=new di(e,t);return new Proxy({},n)}(t,o);Object.defineProperty(t,o,{get:ui(n),enumerable:!0,configurable:!0})}if(function(e,t){let n=In.get(e);n||(n=new WeakMap,In.set(e,n)),n.set(t,!0)}(t,e),b in t){const e=t[b];"function"==typeof e?e.call(t,o).catch(e=>{j(`Error in ${b}: ${e instanceof Error?e.message:String(e)}`)}):j(`${b} is not a function.`)}}function pi(e){const t=new Set,n=new Set,o=function(e){let t={},n=e;for(;n&&n!==Object.prototype;)Object.assign(t,Object.getOwnPropertyDescriptors(n)),n=Object.getPrototypeOf(n);return t}(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterPaths:t,setterPaths:n}}class hi extends ps{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return Ts(e)}__state;_hasUpdatedCallback=!1;_crossRowListPaths=new Set;_name="default";_initialized=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new Vs}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_dcc=!1;_connectGeneration=0;_streamsStartedGeneration=0;constructor(){super(),this._initializePromise=new Promise(e=>{this._resolveInitialize=e}),this._connectedCallbackPromise=new Promise(e=>{this._resolveConnectedCallback=e}),this._loadingPromise=new Promise(e=>{this._resolveLoading=e}),this._setStatePromise=new Promise(e=>{this._resolveSetState=e})}get _state(){return void 0===this.__state&&j(`${n.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){this._commandTokenNames=function(e){const t=new Set,n=e[w];if(void 0===n)return t;Array.isArray(n)||j(`${w} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||j(`${w} entries must be non-empty strings.`),e===N&&j(`${w} entry "${e}" conflicts with the reserved namespace name "${N}".`),t.has(e)&&j(`${w} entry "${e}" is duplicated.`),t.add(e);return t}(t),this._eventTokenNames=function(e){const t=new Set,n=e[v];if(void 0===n)return t;Array.isArray(n)||j(`${v} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||j(`${v} entries must be non-empty strings.`),t.has(e)&&j(`${v} entry "${e}" is duplicated.`),t.add(e);return t}(t),this.__state=t,this._hasUpdatedCallback=g in t,St(this),function(e,t,n){const o=t[S];if(void 0!==o){"object"==typeof o&&null!==o||j(`${S} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||j(`${S} entry "${t}" is not declared in $eventTokens.`),"function"!=typeof s&&j(`${S} entry "${t}" must be a function.`),vt(e,t).subscribe(s)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const n=pi(t);for(const e of n.getterPaths)this._getterPaths.add(e);for(const e of n.setterPaths)this._setterPaths.add(e);var o;hr(this),rr(o=this),tr(o),or.delete(o),cr(this,t),this._initialized&&null!==this._rootNode&&!e()&&(br(this),this._streamsStartedGeneration=this._connectGeneration),this._resolveLoading?.()}get name(){return this._name}_loadFromSsrElement(){if(!this.hasAttribute("enable-ssr"))return null;const e=this.getAttribute("name")||"default",t=this.parentNode;if(!t)return null;const n=ws.findByName(t,e);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 e=this.getAttribute("state");this._state=function(e){const t=document.getElementById(e);if(t&&"application/json"===t.type)try{return JSON.parse(t.textContent||"{}")}catch(e){j("Failed to parse JSON from script element:"+e)}return{}}(e)}else if(this.hasAttribute("src")){const e=this.getAttribute("src");e&&e.endsWith(".json")?this._state=await async function(e){try{const t=await fetch(e);return t.ok||j(`Failed to fetch JSON file: ${t.statusText}`),await t.json()}catch(e){return console.error("Failed to load JSON file:",e),{}}}(e):e&&e.endsWith(".js")?this._state=await Us(e):j(`Unsupported src file type: ${e}`)}else if(this.hasAttribute("json")){const e=this.getAttribute("json");this._state=JSON.parse(e)}else{const e=this.querySelector('script[type="module"]');if(e)this._state=await qs(e,`${this._name}`);else{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${n.tagNames.state}> element with name="${this._name}".`)},6e4);this._state=await this._setStatePromise,clearTimeout(e)}}}catch(e){j(`Failed to initialize state: ${e}`)}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",ks(this.rootNode,this._name,this)}async _initializeBindWebComponent(){if(this.hasAttribute("bind-component")){const e=this.parentNode,t=e instanceof ShadowRoot?e.host:e instanceof Element?e:null,o=t?E(t):null;null!==t&&null!==o||j(`"bind-component" requires <${n.tagNames.state}> to be a direct child of a custom element.`),e instanceof ShadowRoot||this.hasAttribute("name")||j('"bind-component" in Light DOM requires a "name" attribute to avoid namespace conflicts with the parent scope.');const s=this.getAttribute("bind-component");await customElements.whenDefined(o.toLowerCase()),t.hasAttribute(n.bindAttributeName)&&await a(t),s in t||j(`Component does not have property "${s}" for state binding.`);const r=t[s];"object"==typeof r&&null!==r||j(`Component property "${s}" is not an object for state binding.`),this._boundComponent=t,this._boundComponentStateProp=s,fi(this,this._boundComponent,this._boundComponentStateProp,r)}}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{h in e&&await e[Oe]()})}async _initializeDCC(e,t){let o;try{if(this.hasAttribute("src")){const e=this.getAttribute("src");e.endsWith(".js")?o=await Us(e):j(`DCC: Unsupported src type: ${e}`)}else{const t=this.querySelector('script[type="module"]');t?o=await qs(t,e.tagName.toLowerCase()):j(`DCC: No state source found for "${e.tagName.toLowerCase()}".`)}}catch(e){j(`DCC: Failed to load state: ${e}`)}!function(e,t,o){const s=e.tagName.toLowerCase();if(s.includes("-")||j(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`),customElements.get(s))return void console.warn(`[@wcstack/state] DCC: "${s}" is already registered. Skipping redefinition.`);const r=document.createElement("template");r.innerHTML=t.innerHTML;const i=t.mode,a=Array.isArray(o[y])?o[y]:[],c=a.length>0?function(e,t){return{protocol:"wc-bindable",version:1,properties:t.map(t=>({name:t,event:`${e}:${t}-changed`})),inputs:t.map(e=>({name:e}))}}(s,a):null,l=a.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(s,a):{},d=`${n.tagNames.state}:not([name])`,u=class extends HTMLElement{static template=r;static shadowRootMode=i;static wcBindable=c;static bindableEventMap=l;_shadow=null;connectedCallback(){if(!this.hasAttribute(_)&&(this._shadow=this.attachShadow({mode:u.shadowRootMode}),this._shadow.appendChild(u.template.content.cloneNode(!0)),Object.keys(u.bindableEventMap).length>0)){const e=this._shadow.querySelector(d);e&&e.initializePromise.then(()=>{e.setBindableEventMap(u.bindableEventMap)})}}get stateElement(){return this._shadow?.querySelector(d)}},f=Object.getOwnPropertyDescriptors(o);for(const[e,t]of Object.entries(f)){if(xr(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=Sr(e,o)}else n.get=Nr(e),n.set=vr(e);Object.defineProperty(u.prototype,e,n)}customElements.define(s,u)}(e,t,o),this._dcc=!0,this._initialized=!0,this._rootNode=null,this._resolveInitialize?.(),this._resolveConnectedCallback?.()}_callStateDisconnectedCallback(){this.createState("writable",e=>{m in e&&e[De]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initialized)this._dcc||$s(this._rootNode,this._name)===this||ks(this._rootNode,this._name,this);else{const e=this.parentNode;if(e instanceof ShadowRoot&&e.host.hasAttribute(_))return void await this._initializeDCC(e.host,e);await this._initializeBindWebComponent(),await this._initialize(),this._initialized=!0,this._resolveInitialize?.()}if(this.hasAttribute("enable-ssr")&&!e()||await this._callStateConnectedCallback(),e()&&this.hasAttribute("enable-ssr")){await Ts(this.rootNode);const e=this.getAttribute("name")||"default",t=ws.extractStateData(this),o=document.createElement(n.tagNames.ssr);o.setAttribute("name",e),o.setAttribute("version",fs),ws.buildContent(o,t),this.parentNode?.insertBefore(o,this)}e()||null===this._rootNode||t!==this._connectGeneration||this._streamsStartedGeneration===t||br(this),this._resolveConnectedCallback?.()}disconnectedCallback(){if(null!==this._rootNode)try{this._callStateDisconnectedCallback()}finally{ks(this.rootNode,this._name,null),e=this,Hs.delete(e),function(e){Js.delete(e)}(this),St(this),rr(this),hr(this),this._rootNode=null}var e}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}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&&j("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(e){this._bindableEventMap=e}_addDependency(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(e,t){return this._addDependency(this._dynamicDependency,e,t)}addStaticDependency(e,t){return this._addDependency(this._staticDependency,e,t)}setPathInfo(e,t){if("for"===t&&(this._listPaths.add(e),this._elementPaths.add(e+"."+l)),!this._pathSet.has(e)){const t=T(e);if(this._pathSet.add(e),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=T(e.parentPath)}}}_createState(e,t,n){try{const o=function(e,t,n,o){const s=new Xr(e,n,o);return new Proxy(t,s)}(e,this._state,this._name,t);return n(o)}finally{}}async createStateAsync(e,t){return await this._createState(this.rootNode,e,t)}createState(e,t){this._createState(this.rootNode,e,t)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(e){this._crossRowListPaths.add(e)}bindProperty(e,t){Object.defineProperty(this._state,e,t),e===g&&(this._hasUpdatedCallback=!0)}setInitialState(e){this._initialized?this._state=e:this._resolveSetState?.(e)}}function mi(){customElements.get(n.tagNames.ssr)||customElements.define(n.tagNames.ssr,ws),customElements.get(n.tagNames.state)||customElements.define(n.tagNames.state,hi)}function gi(e){var n;e&&((n=e).tagNames&&Object.assign(t.tagNames,n.tagNames),"string"==typeof n.bindAttributeName&&(t.bindAttributeName=n.bindAttributeName),"string"==typeof n.commentTextPrefix&&(t.commentTextPrefix=n.commentTextPrefix),"string"==typeof n.commentForPrefix&&(t.commentForPrefix=n.commentForPrefix),"string"==typeof n.commentIfPrefix&&(t.commentIfPrefix=n.commentIfPrefix),"string"==typeof n.commentElseIfPrefix&&(t.commentElseIfPrefix=n.commentElseIfPrefix),"string"==typeof n.commentElsePrefix&&(t.commentElsePrefix=n.commentElsePrefix),"string"==typeof n.locale&&(t.locale=n.locale),"boolean"==typeof n.debug&&(t.debug=n.debug),"boolean"==typeof n.enableMustache&&(t.enableMustache=n.enableMustache),"boolean"==typeof n.enableDirectionalInitialSync&&(t.enableDirectionalInitialSync=n.enableDirectionalInitialSync),"boolean"==typeof n.enablePropagationContext&&(t.enablePropagationContext=n.enablePropagationContext),"boolean"==typeof n.enableContractAnalyzer&&(t.enableContractAnalyzer=n.enableContractAnalyzer),"boolean"==typeof n.sameValueGuard&&(t.sameValueGuard=n.sameValueGuard)),mi(),zs()}function bi(e){return e}const yi={eq:{description:"等しいか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},ne:{description:"異なるか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},not:{description:"ブール値を反転",hasArgs:!1,resultType:"boolean",acceptTypes:["boolean"],minArgs:0,maxArgs:0},lt:{description:"より小さいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},le:{description:"以下か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},gt:{description:"より大きいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},ge:{description:"以上か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},inc:{description:"加算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},dec:{description:"減算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},mul:{description:"乗算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},div:{description:"除算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mod:{description:"剰余",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},fix:{description:"固定小数点表記",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},locale:{description:"ロケール形式で数値フォーマット",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["string"]},uc:{description:"大文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},lc:{description:"小文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},cap:{description:"先頭文字を大文字に",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},trim:{description:"前後の空白を削除",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},slice:{description:"部分文字列 (start[,end])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},substr:{description:"部分文字列 (pos,len)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},pad:{description:"パディング (length[,char])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},rep:{description:"繰り返し (count)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:1,argTypes:["number"]},rev:{description:"文字順を反転",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},int:{description:"整数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},float:{description:"浮動小数点数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},round:{description:"四捨五入",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},floor:{description:"切り下げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},ceil:{description:"切り上げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},percent:{description:"パーセンテージ形式",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},date:{description:"ロケール形式の日付",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},time:{description:"ロケール形式の時刻",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},datetime:{description:"ロケール形式の日時",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},ymd:{description:"YYYY-MM-DD 形式",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},falsy:{description:"偽値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},truthy:{description:"真値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},defaults:{description:"偽値の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},boolean:{description:"ブール値に変換",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},number:{description:"数値に変換",hasArgs:!1,resultType:"number",acceptTypes:"any",minArgs:0,maxArgs:0},string:{description:"文字列に変換",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},null:{description:"空文字列をnullに変換",hasArgs:!1,resultType:"passthrough",acceptTypes:["string"],minArgs:0,maxArgs:0}},wi=1;function Ni(){return{version:1,syntax:{bindAttribute:n.bindAttributeName,tagName:n.tagNames.state,pathDelimiter:c,wildcard:l,delimiters:{binding:";",propValue:":",modifier:"#",stateName:"@",filter:u},structuralDirectives:Array.from(G)},filters:Object.keys(ee),filterMeta:yi,reservedLifecycle:[h,m,g,b],reservedStateApi:[y,w,N,v,S,x,I,A]}}const vi=new Set(["wcstack.types","wcstack.async","wcstack.platformCapabilities","wcstack.application"]),Si=Object.freeze([]);function xi(e){if(!n.enableContractAnalyzer)return Si;const t=[];return function(e,t,n){const o=e.manifestExtensions;if(null===o||"object"!=typeof o)return;for(const e of Object.keys(o))vi.has(e)||n({type:"contract:unsupported-extension",namespace:e});const s=o["wcstack.types"]?.components;if(null==s)return;for(const[e,o]of Object.entries(s)){const s=t(e);n({type:"contract:manifest-read",tag:e,loaded:null!==s}),null!==s?Ii(e,o,s,n):n({type:"contract:drift",reason:"component-not-loaded",tag:e})}}(e,Ai,e=>{t.push(e),null!==et&&et(e)}),t}function Ii(e,t,n,o){const s=null!==t&&"object"==typeof t?t:{};for(const[t,r]of Object.entries(s.observables??{})){if(!n.propertyEvents.has(t)){o({type:"contract:drift",reason:"missing-member",tag:e,member:t});continue}const s=n.propertyEvents.get(t),i=r?.event;"string"==typeof i&&i!==s&&o({type:"contract:drift",reason:"event-mismatch",tag:e,member:t,sidecarEvent:i,liveEvent:s})}for(const t of Object.keys(s.inputs??{}))n.inputs.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t});for(const t of Object.keys(s.commands??{}))n.commands.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t})}function Ai(e){const t=M(),n=t?.get(e);if(void 0===n)return null;const o=n.wcBindable;if(null===o||"object"!=typeof o||"wc-bindable"!==o.protocol)return null;const s=o,r=new Map;for(const e of Array.isArray(s.properties)?s.properties:[])"string"==typeof e?.name&&"string"==typeof e.event&&r.set(e.name,e.event);const i=new Set;for(const e of Array.isArray(s.inputs)?s.inputs:[])"string"==typeof e?.name&&i.add(e.name);const a=new Set;for(const e of Array.isArray(s.commands)?s.commands:[])"string"==typeof e?.name&&a.add(e.name);return{propertyEvents:r,inputs:i,commands:a}}export{ws as Ssr,fs as VERSION,wi as WCS_MANIFEST_VERSION,xi as analyzeContract,gi as bootstrapState,us as buildBindings,yi as builtinFilterMeta,bi as defineState,Ts as getBindingsReady,o as getConfig,Ni as getWcsManifest};
2
2
  //# sourceMappingURL=index.esm.min.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wcstack/state",
3
- "version": "1.21.1",
3
+ "version": "1.21.2",
4
4
  "description": "Reactive state management with declarative data binding for Web Components. Zero dependencies, buildless.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.esm.js",