@wcstack/state 1.14.0 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- let e=null;function t(){if(null!==e)return e;const t=document.querySelector("html");return e=!!t&&t.hasAttribute("data-wcs-server"),e}const n={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0},o=n;function s(){return o}const r="1.14.0";function i(e){throw new Error(`[@wcstack/state] ${e}`)}const a=new WeakMap;let l=0;function c(e){let t,n=a.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++l,promise:o,resolve:t},a.set(e,n),n}async function d(e){const t=c(e);await t.promise}function u(e){const t=e.node,n=e.replaceNode;t!==n&&null!==t.parentNode&&t.parentNode.replaceChild(n,t)}const f=".",p="*",h=128,m={};for(let e=0;e<128;e++)m[`$${e+1}`]=e;const g=Object.freeze(m),b="$connectedCallback",w="$disconnectedCallback",y="$stateReadyCallback",N="$bindables",S="$commandTokens",x="$command",I="$eventTokens",_="$on",P="data-wc-definition",v=new Map;let $=0;function A(e){let t=v.get(e);return void 0!==t||(t=Object.freeze(new C(e)),v.set(e,t)),t}class C{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:A(t),n=e.split("."),o=[],s=[],r=[],i={},a=[],l=[],c=[],d=[];let u="",f="",h=0;for(let e=0;e<n.length;e++)u+=n[e],n[e]===p&&(r.push(u),i[u]=h,a.push(t(u)),l.push(f),c.push(t(f)),d.push(e),h++),o.push(u),s.push(t(u)),f=u,u+=".";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=l,this.wildcardParentPathSet=new Set(l),this.wildcardParentPathInfos=c,this.wildcardParentPathInfoSet=new Set(c),this.wildcardPositions=d,this.lastWildcardPath=m,this.lastWildcardInfo=m?t(m):null,this.parentPath=g,this.parentPathInfo=g?t(g):null,this.wildcardCount=h}}const E=new WeakMap;function k(e){const t=E.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{E.set(e,n)}}function T(e){if("object"!=typeof e||null===e)return!1;const t=e;return"wc-bindable"===t.protocol&&1===t.version&&Array.isArray(t.properties)}function M(e,t,n){const o="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:o,statePathInfo:A(o),stateName:n,inFilters:[],outFilters:[],bindingType:"prop"}}function O(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function L(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 D=new WeakMap;function W(e){return D.get(e)||null}function R(e,t){D.set(e,t)}const F=new Set(["if","elseif","else","for"]);function B(e){i(`filter ${e} requires at least one option`)}function j(e){i(`filter ${e} requires a number as option`)}function q(e){i(`filter ${e} requires a number value`)}function z(e){i(`filter ${e} requires a date value`)}function H(e){return!(!e||isNaN(Number(e)))}const U={eq:e=>{const t=e?.[0]??B("eq");return e=>"number"==typeof e?(H(t)||j("eq"),e===Number(t)):e===t},ne:e=>{const t=e?.[0]??B("ne");return e=>"number"==typeof e?(H(t)||j("ne"),e!==Number(t)):e!==t},not:e=>e=>("boolean"!=typeof e&&i(`filter ${"not"} requires a boolean value`),!e),lt:e=>{const t=e?.[0]??B("lt");return H(t)||j("lt"),e=>("number"!=typeof e&&q("lt"),e<Number(t))},le:e=>{const t=e?.[0]??B("le");return H(t)||j("le"),e=>("number"!=typeof e&&q("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??B("gt");return H(t)||j("gt"),e=>("number"!=typeof e&&q("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??B("ge");return H(t)||j("ge"),e=>("number"!=typeof e&&q("ge"),e>=Number(t))},inc:e=>{const t=e?.[0]??B("inc");return H(t)||j("inc"),e=>("number"!=typeof e&&q("inc"),e+Number(t))},dec:e=>{const t=e?.[0]??B("dec");return H(t)||j("dec"),e=>("number"!=typeof e&&q("dec"),e-Number(t))},mul:e=>{const t=e?.[0]??B("mul");return H(t)||j("mul"),e=>("number"!=typeof e&&q("mul"),e*Number(t))},div:e=>{const t=e?.[0]??B("div");return H(t)||j("div"),e=>("number"!=typeof e&&q("div"),e/Number(t))},mod:e=>{const t=e?.[0]??B("mod");return H(t)||j("mod"),e=>("number"!=typeof e&&q("mod"),e%Number(t))},fix:e=>{const t=e?.[0]??"0";return H(t)||j("fix"),e=>("number"!=typeof e&&q("fix"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0]??o.locale;return e=>("number"!=typeof e&&q("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]??B("slice");H(n)||j("slice"),t.push(Number(n));const o=e?.[1];return void 0!==o&&(H(o)||j("slice"),t.push(Number(o))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??B("substr");H(t)||j("substr");const n=e?.[1]??B("substr");return H(n)||j("substr"),e=>String(e).substr(Number(t),Number(n))},pad:e=>{const t=e?.[0]??B("pad");H(t)||j("pad");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},rep:e=>{const t=e?.[0]??B("rep");return H(t)||j("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 H(t)||j("round"),e=>{"number"!=typeof e&&q("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return H(t)||j("floor"),e=>{"number"!=typeof e&&q("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return H(t)||j("ceil"),e=>{"number"!=typeof e&&q("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return H(t)||j("percent"),e=>("number"!=typeof e&&q("percent"),`${(100*e).toFixed(Number(t))}%`)},date:e=>{const t=e?.[0]??o.locale;return e=>(e instanceof Date||z("date"),e.toLocaleDateString(t))},time:e=>{const t=e?.[0]??o.locale;return e=>(e instanceof Date||z("time"),e.toLocaleTimeString(t))},datetime:e=>{const t=e?.[0]??o.locale;return e=>(e instanceof Date||z("datetime"),e.toLocaleString(t))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||z("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]??B("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},V=U,J={input:U,output:V},X=(e,t)=>n=>{const o=n[e];return o||i(`filter not found: ${e}`),o(t)};const K=new Map;function Y(e,t){const n=J[t];return e.map(e=>{const o=e.indexOf("("),s=e.lastIndexOf(")");if(-1!==o&&-1===s&&i(`Invalid filter format: missing closing parenthesis in "${e}"`),-1!==s&&-1===o&&i(`Invalid filter format: missing opening parenthesis in "${e}"`),-1===o){const o=e.trim(),s=`${o}():${t}`;let r=K.get(s);return void 0===r&&(r=X(o,[])(n),K.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),l=`${i}(${a.join(",")}):${t}`;let c=K.get(l);return void 0===c&&(c=X(i,a)(n),K.set(l,c)),{filterName:i,args:a,filterFn:c}}})}const G=e=>e.trim(),Q=new Map;const Z=new Map;function ee(e){const t=e.indexOf("|");let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Z.has(s)?r=Z.get(s):(o=s.split("|").map(G),r=Y(o,"output"),Z.set(s,r))):n=e.trim();const[i,a="default"]=n.split("@").map(G);return{stateName:a,statePathName:i,statePathInfo:A(i),outFilters:r}}function te(e){const[...t]=e.split(";").map(G).filter(e=>e.length>0),n=t.map(e=>{const t=e.indexOf(":");-1===t&&i(`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:A("#else"),stateName:"",inFilters:[],outFilters:[],bindingType:"else"}}if("..."===n){const t=ee(o);return t.outFilters.length>0&&i(`Invalid spread binding "${e}": filters are not allowed on spread targets.`),0===t.statePathName.length&&i(`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:[],...ee(o),bindingType:n}}{const e=ee(o),t=function(e){const t=e.indexOf("|");let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Q.has(s)?r=Q.get(s):(o=s.split("|").map(G),r=Y(o,"input"),Q.set(s,r))):n=e.trim();const[i,a]=n.split("#").map(G),l=i.split(".").map(G);return{propName:i,propSegments:l,propModifiers:a?a.split(",").map(G):[],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=>F.has(e.bindingType))&&i(`Invalid bindText: "${e}". 'if', 'elseif', 'else', and 'for' bindings must be single binding.`)}return n}const ne=new WeakMap,oe=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),se=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function re(e){const t=ne.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),s=se.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return oe.has(r)?(ne.set(e,s[2]),s[2]):null}function ie(e){if(e.nodeType===Node.ELEMENT_NODE){return te(e.getAttribute(o.bindAttributeName)||"")}if(e.nodeType===Node.COMMENT_NODE){const t=re(e);null===t&&i("Comment node binding text not found.");const n=So(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o={propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...ee(t),bindingType:"text"},s=null):s=t,[{...o,uuid:s}]}return[]}function ae(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(e){if(e.nodeType===Node.ELEMENT_NODE){return e.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==re(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}const le=new WeakSet;function ce(e,t,n){const s=function(e,t,n={}){const s=n.allowDeferred??!0;if(!t.some(e=>"spread"===e.bindingType))return t;const r=[],a=new WeakSet;for(const n of t){if("spread"!==n.bindingType){r.push(n);continue}e.nodeType!==Node.ELEMENT_NODE&&i("Spread binding requires an element node.");const t=e,o=k(t);null===o&&i(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const l=customElements.get(o);if(void 0===l){s||i(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}const c=l.wcBindable;T(c)||i(`Spread binding "${n.statePathName}" requires <${o}> to declare wcBindable (protocol="wc-bindable", version=1).`);const d=n.statePathName,u=n.stateName,f=new Set;for(const e of c.properties){if(f.has(e.name))continue;f.add(e.name);const t=M(e.name,d,u);a.add(t),r.push(t)}for(const e of c.inputs??[]){if(f.has(e.name))continue;f.add(e.name);const t=M(e.name,d,u);a.add(t),r.push(t)}}const l=new Map;for(let e=0;e<r.length;e++){const t=O(r[e]);null!==t&&l.set(t,e)}const c=[];for(let t=0;t<r.length;t++){const n=O(r[t]);if(null!==n){if(l.get(n)===t)c.push(r[t]);else if(o.debug&&a.has(r[t])){const o=r[l.get(n)],s=e.nodeType===Node.ELEMENT_NODE?`<${e.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[t].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else c.push(r[t])}return c}(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?k(e):null;return null===n&&i("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t}}}le.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 R(e,r),function(e){c(e).resolve()}(e),{bindings:r,deferred:null}}function de(e){const t=ae(e),n=[],o=[];for(const e of t){if(le.has(e))continue;const t=ce(e,ie(e),{allowDeferred:!0});null===t.deferred?n.push(...t.bindings):o.push(t.deferred)}return[t,n,o]}function ue(e){const{node:t,parseResults:n}=e;!function(e){le.delete(e)}(t);return ce(t,n,{allowDeferred:!1}).bindings}const fe=new WeakMap,pe=new WeakMap;class he{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]===p?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=me(e,t)}}function me(e,t){if(null===t){let t=pe.get(e);return void 0!==t||(t=new he(e,null),pe.set(e,t)),t}{let n=fe.get(t);void 0===n&&(n=new WeakMap,fe.set(t,n));let o=n.get(e);return void 0!==o||(o=new he(e,t),n.set(e,o)),o}}class ge{_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 be extends ge{}function we(e){return e instanceof be}const ye=new WeakMap;function Ne(e){let t=e;for(;t;){const e=ye.get(t);if(e)return e;t=t.parentNode}return null}function Se(e,t){null!==t?ye.set(e,t):ye.delete(e)}const xe=Symbol("$$setLoopContextAsync"),Ie=Symbol("$$setLoopContext"),_e=Symbol("$$getByAddress"),Pe=Symbol("$$setByAddress"),ve=Symbol("$$connectedCallback"),$e=Symbol("$$disconnectedCallback"),Ae=Symbol("$$updatedCallback");const Ce=new Map,Ee=new Map;const ke=(e,t,n,o)=>s=>{n.includes("prevent")&&s.preventDefault(),n.includes("stop")&&s.stopPropagation();const r=s.target,a=go(r.getRootNode(),e);null===a&&i(`State element with name "${e}" not found for event handler.`);const l=Ne(r),c=t.startsWith(x+".");a.createStateAsync("writable",async n=>{n[Ie](l,()=>{const r=l?.listIndex.indexes??[];if(c){const e=n[_e](me(o,null));return we(e)||i(`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 a=n[t];return"function"!=typeof a&&i(`Handler "${t}" is not a function on state "${e}".`),Reflect.apply(a,n,[s,...r])})})};function Te(e){if(!e.propName.startsWith("on"))return!1;const t=function(e){const t=e.propModifiers.filter(e=>"prevent"===e||"stop"===e).sort().join(",");return`${e.stateName}::${e.statePathName}::${t}`}(e);let n=Ce.get(t);void 0===n&&(n=ke(e.stateName,e.statePathName,e.propModifiers,e.statePathInfo),Ce.set(t,n));const o=e.propName.slice(2);e.node.addEventListener(o,n);let s=Ee.get(t);return void 0===s?(s=new Set([e]),Ee.set(t,s)):s.add(e),!0}class Me extends ge{}const Oe=new WeakMap;function Le(e,t){let n=Oe.get(e);void 0===n&&(n=new Map,Oe.set(e,n));let o=n.get(t);return void 0===o&&(o=new Me(t),n.set(t,o)),o}function De(e){Oe.delete(e)}const We=new WeakMap;function Re(e){if("eventToken"!==e.propSegments[0])return!1;const t=e.node,n=k(t);if(null!==n&&void 0===customElements.get(n))return customElements.whenDefined(n).then(()=>{Re(e)}),!0;if(We.has(e))return!0;const o=e.propSegments[1];"string"==typeof o&&0!==o.length||i('eventToken binding requires a property name (e.g., "eventToken.error").');const s=function(e){const t=k(e);if(null===t)return null;const n=customElements.get(t),o=n?.wcBindable;return"wc-bindable"===o?.protocol&&1===o?.version?o:null}(t);null===s&&i(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const r=s.properties.find(e=>e.name===o);void 0===r&&i(`Property "${o}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.`);const a=r.event,l=e.statePathName,c=e.stateName,d=e.propModifiers,u=e=>{d.includes("prevent")&&e.preventDefault(),d.includes("stop")&&e.stopPropagation();const n=go(t.getRootNode(),c);null===n&&i(`State element with name "${c}" not found for eventToken handler.`),n.eventTokenNames.has(l)||i(`eventToken "${l}" is not declared in $eventTokens of state "${c}".`);const o=Ne(t);n.createStateAsync("writable",async t=>{t[Ie](o,()=>{const s=o?.listIndex.indexes??[];return Le(n,l).emit(t,e,...s)})})};return t.addEventListener(a,u),We.set(e,{eventName:a,handler:u}),!0}const Fe=new Set(["radio","checkbox"]),Be=new Set(["value","valueAsNumber","valueAsDate"]);const je=new Map,qe=new Map,ze=e=>e.detail;function He(e){const t=k(e.node);if(null!==t){if(void 0===customElements.get(t))return void customElements.whenDefined(t).then(()=>{He(e)})}if(function(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(Fe.has(e)&&"checked"===t)return!0;if(Be.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=k(n);if(null!==s){const e=customElements.get(s);void 0===e&&i(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const n=e.wcBindable;if("wc-bindable"===n?.protocol&&1===n?.version&&n.properties.some(e=>e.name===t))return!0}return!1}(e.node,e.propName)&&-1===e.propModifiers.indexOf("ro")){const t=function(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=k(e.node);if(null!==n){const o=customElements.get(n);void 0===o&&i(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=o.wcBindable;if("wc-bindable"===s?.protocol&&1===s?.version){const n=s.properties.find(t=>t.name===e.propName);n&&(t=n.event)}}for(const n of e.propModifiers)n.startsWith("on")&&(t=n.slice(2));return t}(e),n=function(e){const t=k(e.node);if(null!==t){const n=customElements.get(t);if(n){const t=n.wcBindable;if("wc-bindable"===t?.protocol&&1===t?.version){const n=t.properties.find(t=>t.name===e.propName);if(n)return n.getter??ze}}}return null}(e),o=function(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"}`}(e,t,null!==n);let s=je.get(o);void 0===s&&(s=((e,t,n,o,s)=>r=>{const a=r.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==s)l=s(r);else{if(!(t in a))return void console.warn(`[@wcstack/state] Property "${t}" does not exist on target element.`);l=a[t]}let c=l;for(const e of o)c=e.filterFn(c);const d=go(a.getRootNode(),e);null===d&&i(`State element with name "${e}" not found for two-way binding.`);const u=Ne(a);d.createState("writable",e=>{e[Ie](u,()=>{e[n]=c})})})(e.stateName,e.propName,e.statePathName,e.inFilters,n),je.set(o,s)),e.node.addEventListener(t,s);let r=qe.get(o);void 0===r?(r=new Set([e]),qe.set(o,r)):r.add(e)}}const Ue=new WeakMap;function Ve(e){return Ue.get(e)??[]}function Je(e,t){Ue.set(e,t)}const Xe=new WeakMap;function Ke(e,t){if(Xe.has(e)){const n=Xe.get(e);if(n.has(t))return n.get(t)}else Xe.set(e,new WeakMap);const n=Object.freeze(new Ye(e,t));return Xe.get(e).set(t,n),n}class Ye{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=Ke(e,t.parentPathInfo)}}const Ge=new WeakMap,Qe=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]===p?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAbsoluteAddress=et(e,t)}}function et(e,t){if(null===t){let t=Qe.get(e);return void 0!==t||(t=new Ze(e,null),Qe.set(e,t)),t}{let n=Ge.get(t);void 0===n&&(n=new WeakMap,Ge.set(t,n));let o=n.get(e);return void 0!==o||(o=new Ze(e,t),n.set(e,o)),o}}const tt=new WeakMap;function nt(e,t){null===t?tt.delete(e):tt.set(e,t)}function ot(e){return tt.get(e)||null}const st=new Map;function rt(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=st.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,st.set(s,r),r}const it=new WeakMap;function at(e){const t=Ne(e.node);if(null===t)return null;let n=it.get(t);if(void 0===n)n=new WeakMap,it.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=rt(t.pathInfo,e.statePathInfo);return n>0&&(o=t.listIndex.at(n-1)),o}finally{n.set(e,o)}}const lt=new WeakMap;function ct(e){let t=null;if(t=lt.get(e)||null,null!==t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=ot(n);null===t?i(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}const o=at(e),s=go(n,e.stateName);null===s&&i(`State element with name "${e.stateName}" not found for binding.`);return t=et(Ke(s,e.statePathInfo),o),lt.set(e,t),t}function dt(e){lt.delete(e)}const ut=new WeakMap;function ft(e,t){const n=ut.get(e);return!!n&&!0===n.get(t)}function pt(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const ht=Object.freeze([]);const mt=new WeakMap;const gt=new WeakMap;function bt(e){return gt.get(e)??[]}function wt(e,t){gt.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 yt=0;function Nt(){return`u${(yt++).toString(36)}`}let St=0;class xt{uuid=Nt();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=St}get index(){return this._index}set index(e){this._index=e,this._version=++St,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=St),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 It(e,t){return new xt(e,t)}const _t=new WeakMap;function Pt(e){return _t.get(e)||null}function vt(e,t){null!==t?_t.set(e,t):_t.delete(e)}const $t=new WeakMap,At=Object.freeze([]),Ct=new Set;function Et(e,t,n){const o=Array.isArray(t)&&t.length>0?t:At,s=Array.isArray(n)&&n.length>0?n:At,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:At,o=Array.isArray(t)&&t.length>0?t:At;let s=$t.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Pt(o)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:Ct,deleteIndexSet:new Set(i),addIndexSet:Ct};let t=Pt(s);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=It(e,n);t.push(o)}}return a={oldIndexes:i,newIndexes:t,changeIndexSet:Ct,deleteIndexSet:Ct,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:Ct,deleteIndexSet:Ct,addIndexSet:Ct};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)}if(null!==t)return function(e,t,n,o,s){const r=new Set(o),i=new Set(n),a=new Set,l=r.difference(i),c=i.difference(r);for(let e=0;e<t.length;e++){const o=t[e],r=s.get(o),i=r&&r.length>0?r.shift():void 0;if(void 0!==i){const t=n[i];t.index!==e&&a.add(t)}}return{oldIndexes:n,newIndexes:o,changeIndexSet:a,deleteIndexSet:c,addIndexSet:l}}(0,s,i,t,n);t=[];const r=new Set,l=new Set;for(let o=0;o<s.length;o++){const a=s[o],c=n.get(a),d=c&&c.length>0?c.shift():void 0;if(void 0===d){const n=It(e,o);t.push(n),l.add(n)}else{const e=i[d];e.index!==o&&(e.index=o,r.add(e)),t.push(e)}}return a={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:l}}finally{void 0!==a&&(!function(e,t,n){let o=$t.get(e);o||(o=new WeakMap,$t.set(e,o)),o.set(t,n)}(o,s,a),vt(s,a.newIndexes))}}const kt=new WeakMap;function Tt(e){let t=null;return t=kt.get(e)||null,null===t&&(t=new Set,kt.set(e,t)),t}function Mt(e,t){Tt(e).add(t)}function Ot(e,t){Tt(e).delete(t)}const Lt=new WeakMap;function Dt(e){Lt.delete(e)}const Wt=new WeakMap;function Rt(e){return Wt.get(e)??[]}function Ft(e,t){Wt.set(e,t)}const Bt=new WeakMap;function jt(e){return Bt.get(e)??[]}function qt(e,t){Bt.set(e,t)}function zt(e,t){const n=jt(e);for(const e of n)Se(e,t)}function Ht(e,t,n){zt(e,t);const o=Rt(e);for(const e of o){Mt(ct(e),e),$n(e,n)}}function Ut(e){if(!e.mounted)return;const t=Rt(e);for(const e of t){Ot(ct(e),e),dt(e),Dt(e)}!function(e){const t=jt(e);for(const e of t)Se(e,null)}(e)}const Vt=new WeakMap,Jt=Object.freeze(new Set);function Xt(e,t){const n=Vt.get(e);n?n.add(t):Vt.set(e,new Set([t]))}function Kt(e){const t=Vt.get(e);return void 0!==t?t:Jt}const Yt=new Set(["if","elseif","else","for"]);class Gt{_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(){for(const e of this._childNodeArray)null!==e.parentNode&&e.parentNode.removeChild(e);const e=Rt(this);for(const t of e){if(Yt.has(t.bindingType)){const e=Kt(t.node);for(const t of e)t.unmount()}Dt(t),dt(t)}this._mounted=!1}}function Qt(e){const t=document.createDocumentFragment(),n=new Gt(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 Zt(e){void 0!==e.uuid&&null!==e.uuid||i("BindingInfo.uuid is null.");const t=So(e.uuid);t||i(`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=L(e,s.nodePath);if(null===t&&i(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),le.has(t))continue;const r=ce(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t);return Wn(o),{nodes:n,bindingInfos:o}}(n,t.nodeInfos),s=new Gt(n);Ft(s,o.bindingInfos);const r=[];for(const e of o.bindingInfos)e.statePathName in g&&r.push(e);return wt(s,r),qt(s,o.nodes),Xt(e.node,s),s}const en=new WeakMap,tn=new WeakMap,nn=new WeakMap,on=new WeakMap;function sn(e,t,n){dn(e,t,n)}function rn(e,t){en.set(e,t)}function an(e){return nn.get(e.node)||[]}function ln(e,t){const n=nn.get(e.node);void 0===n?nn.set(e.node,[t]):n.push(t)}function cn(e,t){let n=tn.get(e);if(void 0===n)return null;const o=n.get(t);return void 0===o?null:o}function dn(e,t,n){let o=tn.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,tn.set(e,o)}null===n?o.delete(t):o.set(t,n)}const un=new WeakMap;function fn(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function pn(e,n,s){const r=e.node.isConnected,i=Boolean(s);let a;const l=Kt(e.node);a=0===l.size?Zt(e):l.values().next().value;const c=t(),d=e.uuid??"",u=e.bindingType;try{if(i||(o.debug&&console.log(`unmount if content : ${fn(e)}`),Ut(a),a.unmount()),i){if(o.debug&&console.log(`mount if content : ${fn(e)}`),c){const t=document.createComment(`@@wcs-${u}-start:${d}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),a.mountAfter(t);const n=document.createComment(`@@wcs-${u}-end:${d}:${e.statePathName}`),o=a.lastNode??t;o.parentNode.insertBefore(n,o.nextSibling)}else a.mountAfter(e.node);Ht(a,Ne(e.node),n)}}finally{un.set(e.node,r)}}const hn=new WeakMap;function mn(e){return hn.get(e)??[]}const gn=new Set;const bn={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 wn(e,n,s){if(void 0===s)return void(o.debug&&console.debug("Skipped property write: state value is undefined.",{element:e.node,propSegments:e.propSegments,statePathName:e.statePathName}));const r=e.node,i=e.propSegments;if(1===i.length){const e=i[0];if(r[e]!==s){let t=!1;try{r[e]=s,t=!0}catch(t){o.debug&&console.warn(`Failed to set property '${e}' on element.`,{element:r,newValue:s,error:t})}if(t){const t=function(e,t){const n=k(e);if(null===n)return null;const o=customElements.get(n);if(void 0===o)return null;const s=o.wcBindable;if("wc-bindable"!==s?.protocol||1!==s?.version)return null;const r=s.inputs;if(!Array.isArray(r))return null;for(const e of r)if(e.name===t&&"string"==typeof e.attribute&&e.attribute.length>0)return e.attribute;return null}(r,e);if(null!==t)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,t,s)}catch(e){o.debug&&console.warn(`Failed to mirror attribute '${t}' on element.`,{element:r,newValue:s,error:e})}}}if(t()){const t=bn[e];t?t(r,s):(!function(e,t,n){let o=hn.get(e);o||(o=[],hn.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,e,s),a=r,gn.add(a))}return}var a;let l=r[i[0]];for(let e=1;e<i.length-1;e++){const t=i[e];if(null==l)return;l=l[t]}const c=l[i[i.length-1]];if(c!==s){if(Object.isFrozen(l))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:c,newValue:s}));try{l[i[i.length-1]]=s}catch(e){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:c,newValue:s,error:e})}}}const yn=new WeakSet;function Nn(e,t,n){const o=e.node,s=e.propSegments;s.length<=1&&i(`Invalid propSegments for web component binding: ${s.join(".")}`);const[r,...a]=s,l=o[r];void 0===l&&i(`Property "${r}" not found on web component.`),l[a.join(".")]=n}function Sn(e,t){const n=function(e){let t=null;if(t=Lt.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=at(e);null===n&&i(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=me(e.statePathInfo,n)}else t=me(e.statePathInfo,null);return Lt.set(e,t),t}(t);if(n.pathInfo.path in g){const e=Ne(t.node);return null===e&&i(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&i("ListIndex not found for loopContext:");const n=g[t];void 0===n&&i(`Invalid index name: ${t}`);const o=e.listIndex.at(n);return null===o&&i(`Index not found at position ${n} for loopContext:`),o.index}(e,n.pathInfo.path)}return e[_e](n)}const xn={class:function(e,t,n){const o=e.node,s=e.propSegments[1];"boolean"!=typeof n&&i("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){we(n)||i("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=mt.get(e);if(s&&s.token===o)return;const r=e.node,a=e.propSegments[1];"string"==typeof a&&0!==a.length||i('command binding requires a method name (e.g., "command.fetch").');const l=function(e){const t=k(e);if(null===t)return null;const n=customElements.get(t);void 0===n&&i(`Custom element <${t}> is not defined for command binding.`);const o=n.wcBindable;return"wc-bindable"===o?.protocol&&1===o?.version?o:null}(r);null===l&&i(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),Array.isArray(l.commands)&&l.commands.some(e=>e.name===a)||i(`Command "${a}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.`),s&&(s.unsubscribe(),mt.delete(e));const c=new WeakRef(r);let d=null;d=o.subscribe((...t)=>{const n=c.deref();if(!n||!n.isConnected)return d?.(),void mt.delete(e);const o=n[a];return"function"!=typeof o&&i(`Method "${a}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),mt.set(e,{token:o,unsubscribe:d,elementRef:c})}},In={text:function(e,n,o){if(e.replaceNode.nodeValue!==o&&(e.replaceNode.nodeValue=o),t()&&!yn.has(e.replaceNode)){yn.add(e.replaceNode);const t=e.replaceNode.parentNode;if(t){const n=e.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);t.insertBefore(o,e.replaceNode),t.insertBefore(s,e.replaceNode.nextSibling)}}},for:function(e,n,o){const s=e.statePathInfo,r=at(e),a=ct(e),l=Ve(a),c=Et(r,l,o);if(n.newListValueByAbsAddress.set(a,Array.isArray(o)?o:[]),Array.isArray(l)&&l.length===c.deleteIndexSet.size&&c.deleteIndexSet.size>0&&null!==e.node.parentNode){let t=on.get(e.node);if(void 0===t){const n=en.get(e.node)||e.node;t=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}(e.node,n),on.set(e.node,t)}if(t){const t=e.node.parentNode;t.textContent="",t.appendChild(e.node)}}for(const t of c.deleteIndexSet){const n=cn(e.node,t);null!==n&&(Ut(n),n.unmount(),ln(e,n),dn(e.node,t,null))}let d=e.node;const u=A(s.path+"."+p),f=n.stateElement.loopContextStack;let h=null;c.newIndexes.length==c.addIndexSet.size&&c.newIndexes.length>0&&d.isConnected&&(h=document.createDocumentFragment(),nt(h,n.rootNode));const m=t(),g=e.uuid??"";for(const t of c.newIndexes){let o;if(c.addIndexSet.has(t)){const r=me(u,t);f.createLoopContext(r,r=>{const i=an(e);if(o=i.pop(),void 0===o&&(o=Zt(e)),null!==h)m&&h.appendChild(document.createComment(`@@wcs-for-start:${g}:${s.path}:${t.index}`)),o.appendTo(h),m&&h.appendChild(document.createComment(`@@wcs-for-end:${g}:${s.path}:${t.index}`));else{if(d.nextSibling!==o.firstNode){if(m){const e=document.createComment(`@@wcs-for-start:${g}:${s.path}:${t.index}`);d.parentNode.insertBefore(e,d.nextSibling),d=e}o.mountAfter(d)}if(m){const e=document.createComment(`@@wcs-for-end:${g}:${s.path}:${t.index}`),n=o.lastNode??d;n.parentNode.insertBefore(e,n.nextSibling)}}Ht(o,r,n)}),void 0===o&&i(`Content not found for ListIndex: ${t.index} at path "${s.path}"`)}else{if(o=cn(e.node,t),c.changeIndexSet.has(t)){const e=bt(o);for(const t of e)$n(t,n)}null===o&&i(`Content not found for ListIndex: ${t.index} at path "${s.path}"`),d.nextSibling!==o.firstNode&&o.mountAfter(d)}d=o.lastNode||d,dn(e.node,t,o)}en.set(e.node,d),null!==h&&(e.node.parentNode.insertBefore(h,e.node.nextSibling),nt(h,null))},if:pn,else:pn,elseif:pn,radio:function(e,t,n){const o=e.node,s=pt(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=pt(o.value,e.inFilters),r=Array.isArray(n)?n:ht;o.checked=r.includes(s)}},_n=new WeakMap,Pn=new WeakMap;function vn(e,t){const n=pt(Sn(t.state,e),e.outFilters);if(!0===Pn.get(e))return void t.deferredSelectBindings.push({binding:e,value:n});let o=_n.get(e);if(void 0===o){if(_n.has(e))return ft(e.replaceNode,t.stateElement)?(o=Nn,_n.set(e,o)):o=wn,void o(e,t,n);if(o=In[e.bindingType],void 0===o){const n=e.propSegments[0];if(o=xn[n],_n.set(e,o),void 0===o){k(e.replaceNode)?ft(e.replaceNode,t.stateElement)?(o=Nn,_n.set(e,o)):o=wn:(o=wn,_n.set(e,o))}}if(o===wn){if("SELECT"===e.node.tagName){const o=e.propSegments[0];if("value"===o||"selectedIndex"===o)return t.deferredSelectBindings.push({binding:e,value:n}),void Pn.set(e,!0)}}o(e,t,n)}else o(e,t,n)}function $n(e,t){if(t.appliedBindingSet.has(e))return;t.appliedBindingSet.add(e);const n=ct(e);if(t.updatedAbsAddressSetByStateElement.has(t.stateElement)){t.updatedAbsAddressSetByStateElement.get(t.stateElement).add(n)}else t.updatedAbsAddressSetByStateElement.set(t.stateElement,new Set([n]));if("event"===e.bindingType)return;const o=k(e.replaceNode);if(o&&void 0===customElements.get(o))return;let s=e.replaceNode.getRootNode();if(s instanceof DocumentFragment&&!(s instanceof ShadowRoot)&&(s=ot(s),null===s&&i("Root node for fragment not found for binding.")),e.stateName!==t.stateName||s!==t.rootNode){const n=go(s,e.stateName);null===n&&i(`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};vn(e,r)})}else vn(e,t)}function An(e){let t=0;const n=new Set,s=new Map,r=new Map,a=[];for(;t<e.length;){let l=e[t];const c=l.stateName;if(!1===l.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${l.bindingType} ${l.statePathName} on ${l.node.nodeName}`,l),t++;continue}let d=l.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=ot(d),null===d&&i("Root node for fragment not found for binding."));const u=go(d,c);null===u&&i(`State element with name "${c}" not found for binding.`),u.createState("readonly",o=>{const i={rootNode:d,stateName:c,stateElement:u,state:o,appliedBindingSet:n,newListValueByAbsAddress:s,updatedAbsAddressSetByStateElement:r,deferredSelectBindings:a};for(;;){$n(l,i),t++;const n=e[t];if(!n)break;const o=n.replaceNode.getRootNode();if(n.stateName!==c||o!==i.rootNode)break;l=n}})}for(const{binding:e,value:t}of a)wn(e,0,t);for(const[e,t]of s.entries())Je(e,t);for(const[e,t]of r.entries())e.createState("writable",e=>{e[Ae](Array.from(t))})}const Cn=new Map,En=new Map;const kn=(e,t,n)=>o=>{const s=o.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 n)r=e.filterFn(r);const a=go(s.getRootNode(),e);null===a&&i(`State element with name "${e}" not found for two-way binding.`);const l=Ne(s);a.createState("writable",e=>{e[Ie](l,()=>{e[t]=r})})};function Tn(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf("ro")){const t=function(e){let t="input";for(const n of e.propModifiers)n.startsWith("on")&&(t=n.slice(2));return t}(e),n=function(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.stateName}::${e.statePathName}::${t}::${n}`}(e,t);let o=Cn.get(n);void 0===o&&(o=kn(e.stateName,e.statePathName,e.inFilters),Cn.set(n,o)),e.node.addEventListener(t,o);let s=En.get(n);return void 0===s?(s=new Set([e]),En.set(n,s)):s.add(e),!0}return!1}const Mn=new Map,On=new Map;const Ln=(e,t,n)=>o=>{const s=o.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 a=s.value;for(const e of n)a=e.filterFn(a);const l=go(s.getRootNode(),e);null===l&&i(`State element with name "${e}" not found for two-way binding.`);const c=Ne(s);l.createState("writable",e=>{e[Ie](c,()=>{let n=e[t];if(Array.isArray(n))if(r)-1===n.indexOf(a)&&(e[t]=n.concat(a));else{const o=n.indexOf(a);-1!==o&&(e[t]=n.toSpliced(o,1))}else e[t]=r?[a]:[]})})};function Dn(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf("ro")){const t=function(e){let t="input";for(const n of e.propModifiers)n.startsWith("on")&&(t=n.slice(2));return t}(e),n=function(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.stateName}::${e.statePathName}::${t}::${n}`}(e,t);let o=Mn.get(n);void 0===o&&(o=Ln(e.stateName,e.statePathName,e.inFilters),Mn.set(n,o)),e.node.addEventListener(t,o);let s=On.get(n);return void 0===s?(s=new Set([e]),On.set(n,s)):s.add(e),!0}return!1}function Wn(e){for(const t of e)u(t),Te(t)||Re(t)||(He(t),Tn(t),Dn(t))}function Rn(e){for(const t of e){Mt(ct(t),t);const e=go(t.replaceNode.getRootNode(),t.stateName);null===e&&i(`State element with name "${t.stateName}" not found for binding.`),"event"!==t.bindingType&&e.setPathInfo(t.statePathName,t.bindingType)}}function Fn(e,t){const[n,o,s]=de(e);for(const e of n)Se(e,t);Wn(o),Rn(o),An(o),function(e,t){for(const n of e)customElements.whenDefined(n.tagName).then(()=>{if(!n.node.isConnected)return;const e=ue(n);0!==e.length&&(Se(n.node,t),Wn(e),Rn(e),An(e))}).catch(e=>{console.error(`[@wcstack/state] deferred spread failed for <${n.tagName}>.`,e)})}(s,t)}const Bn=/\{\{\s*(.+?)\s*\}\}/g,jn=new Set(["SCRIPT","STYLE"]);function qn(e){if(!o.enableMustache)return;!function(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[];for(;t.nextNode();)n.push(t.currentNode);for(const e of n)e.parentElement&&jn.has(e.parentElement.tagName)||zn(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),qn(t.content)}else qn(e.content)}function zn(e){const t=e.data;if(Bn.lastIndex=0,!Bn.test(t))return;Bn.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=Bn.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 Hn;function Un(){if(Hn)return Hn;const e=[],t=X("not",e)(V);return Hn={filterName:"not",args:e,filterFn:t},Hn}const Vn=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Jn(e,t){const n=t+f+p,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+f+r.slice(1)}return i.length>0?r+i:r}function Xn(e,t){const n=Vn.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+Jn(s,t)+r}function Kn(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=Jn(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function Yn(e,t){return Kn(e,t)}function Gn(e,t){const n=o.bindAttributeName,s=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const e=s.currentNode;if(e.nodeType===Node.COMMENT_NODE){const n=e;n.data=Xn(n.data,t);continue}const o=e;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const e=Kn(r,t);e!==r&&o.setAttribute(n,e)}}}function Qn(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 Zn(e){const t=[],n=ae(e);for(const e of n){const n=ie(e);t.push({nodePath:Qn(e),parseBindTextResults:n})}return t}function eo(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 to=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),no=Un();function oo(e,t){const n=t.outFilters;return{...t,outFilters:[...n,no],bindingType:e}}function so(e,t,n,o){eo(t),"string"==typeof o&&Gn(t,o),ro(e,t,o);return{fragment:t,parseBindTextResult:n,nodeInfos:Zn(t)}}function ro(e,t,n){const s=o.commentElsePrefix,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode(e){const t=e;if("template"===t.tagName.toLowerCase()){if((t.getAttribute(o.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let a=null;const l=[],c=[];for(;r.nextNode();){const e=r.currentNode;c.push(e)}for(const t of c){let r=t.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(r=Yn(r,n));let c=te(r)[0];const d=to.get(c.bindingType);if(void 0===d)continue;const u=c.bindingType,f=t.content,p=Nt();let h=null;const m="for"===u?c.statePathName:n;if("else"===u){null===a&&i("'else' binding found without preceding 'if' or 'elseif' binding."),c=oo("else",a.parseBindTextResult),h=so(e,f,c,m),No(p,e,h);const n=l.at(-1),o=document.createComment(`@@${d}:${p}`);void 0!==n?(t.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:Qn(o),parseBindTextResults:ie(o)})):t.replaceWith(o)}else if("elseif"===u){null===a&&i("'elseif' binding found without preceding 'if' or 'elseif' binding."),h=so(e,f,c,m),No(p,e,h);const n=document.createComment(`@@${d}:${p}`),o=Nt(),r={fragment:document.createDocumentFragment(),parseBindTextResult:oo("else",a.parseBindTextResult),nodeInfos:[]};r.fragment.appendChild(n),r.nodeInfos.push({nodePath:Qn(n),parseBindTextResults:ie(n)}),No(o,e,r);const u=l.at(-1);l.push(r);const g=document.createComment(`@@${s}:${o}`);void 0!==u?(t.remove(),u.fragment.appendChild(g),u.nodeInfos.push({nodePath:Qn(g),parseBindTextResults:ie(g)})):t.replaceWith(g)}else{h=so(e,f,c,m),No(p,e,h);const n=document.createComment(`@@${d}:${p}`);t.replaceWith(n)}"if"===u?(l.length=0,a=h):"elseif"===u?a=h:"else"===u&&(a=null,l.length=0)}}async function io(e){const t=e.querySelectorAll(o.tagNames.state),n=[];await customElements.whenDefined(o.tagNames.state);for(const e of t){const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function ao(e){if(e===document)await io(document),qn(document),ro(document,document),Fn(document.body,null);else{const t=e;t.host.hasAttribute(o.bindAttributeName)&&await d(t.host),await io(t),qn(t),ro(t,t),Fn(t,null)}}const lo=new Set(["for","if","elseif","else"]);function co(e){if(0===e.length)return{bindingInfos:[],subscriberNodes:[]};const t=e[0].parentNode,n=e[e.length-1].nextSibling,o=document.createElement("div");for(const t of e)o.appendChild(t);const[s,r]=de(o);for(const e of r)u(e),Te(e)||Re(e)||(He(e),Tn(e),Dn(e));if(t)for(;o.firstChild;)t.insertBefore(o.firstChild,n);return{bindingInfos:r,subscriberNodes:s}}function uo(e,t,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[t];if(!s)return null;const r=`@@${s}:${n}`,i=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const e=i.currentNode;if(e.data===r)return e}return null}function fo(e,t){const n=e;let s=null;for(const[e,r]of t.templates){let t=te(r.getAttribute(o.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&s?t={...s,outFilters:[...s.outFilters,Un()],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),l="for"===i?t.statePathName:void 0;eo(a),"string"==typeof l&&Gn(a,l),ro(n,a,l);No(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:Zn(a)})}}async function po(e){await io(e);const t=e.querySelectorAll(o.tagNames.ssr);for(const n of t){const t=n;if(!t.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${t.version}", client="${r}". Falling back to full render.`),vo.cleanupDom(e),!1}for(const n of t)fo(e,n);const n=function(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const e of o){const n=Io.exec(e.data);if(!n)continue;const o=n[1],s=n[2],r=s.split(":");let i,a,l=null;"for"===o?(i=r[0],a=r[1],l=parseInt(r[2],10)):(i=r[0],a=r.slice(1).join(":"));const c=[];let d=e.nextSibling;const u=`@@wcs-${o}-end:${s}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)c.push(d),d=d.nextSibling;t.push({type:o,uuid:i,path:a,index:l,nodes:c})}return t}(document.body);!function(e,t){const n=new Map;for(const o of t){if(0===o.nodes.length)continue;const t=Qt(o.nodes),{bindingInfos:s,subscriberNodes:r}=co(o.nodes);for(const e of r)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");Ft(t,s),qt(t,r);const i=[];for(const e of s)e.statePathName in g&&i.push(e);if(wt(t,i),"for"===o.type&&null!==o.index){const r=uo(e,"for",o.uuid);if(r){const e=It(null,o.index);sn(r,e,t),rn(r,o.nodes[o.nodes.length-1]),Xt(r,t),zt(t,me(A(o.path+"."+p),e));for(const e of s)Mt(ct(e),e);let i=n.get(o.uuid);i||(i=[],n.set(o.uuid,i)),i.push(e)}}else{const n=uo(e,o.type,o.uuid);if(n){Xt(n,t);for(const e of s)Mt(ct(e),e)}}}for(const[t,o]of n){const n=uo(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=So(t);if(!r)continue;const i=r.parseBindTextResult.stateName,a=r.parseBindTextResult.statePathName,l=go(s,i);l&&l.createState("readonly",e=>{const t=e[a];Array.isArray(t)&&vt(t,o)})}}(document.body,n),vo.removeBlockBoundaryComments(document.body);const s=[];for(const e of t)e.parentNode&&(s.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());vo.restoreTextBindings(document.body);const[a,l]=de(document.body);for(const e of a)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||(Se(e,null),t.setAttribute("data-wcs-completed",""))}else Se(e,null);const c=[],d=[];for(const e of l)if(u(e),!Te(e)&&!Re(e))if(He(e),Tn(e),Dn(e),lo.has(e.bindingType))d.push(e);else{if(e.statePathName.includes(p))continue;c.push(e)}for(const e of[...c,...d]){Mt(ct(e),e);const t=go(e.replaceNode.getRootNode(),e.stateName);null===t&&i(`State element with name "${e.stateName}" not found for binding.`),"event"!==e.bindingType&&t.setPathInfo(e.statePathName,e.bindingType)}for(const e of d)if("for"===e.bindingType){const t=ct(e),n=go(e.replaceNode.getRootNode(),e.stateName);n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&Je(t,o)})}An(c);for(const{el:e,parent:t,next:n}of s)t.insertBefore(e,n);const f=e.querySelectorAll(o.tagNames.ssr);for(const t of f){const n=t.hydrateProps;for(const[t,o]of Object.entries(n)){const n=e.querySelector(`[data-wcs-ssr-id="${t}"]`);if(n)for(const[e,t]of Object.entries(o))n[e]=t}}const h=e.querySelectorAll("[data-wcs-completed]");for(const e of h)e.removeAttribute("data-wcs-completed");return!0}const ho=new WeakMap,mo=new WeakMap;function go(e,t){let n=ho.get(e);return n&&n.get(t)||null}function bo(e){return mo.get(e)??Promise.resolve()}function wo(e,n,s){let r=ho.get(e);if(null===s){if(!r)return;r.delete(n),0===r.size&&ho.delete(e),o.debug&&console.debug(`State element unregistered: name="${n}"`)}else{if(!r){r=new Map,ho.set(e,r);const n=!t()&&s.hasAttribute?.("enable-ssr");if("HTMLDocument"===e.constructor.name||"Document"===e.constructor.name){const t=new Promise(t=>{queueMicrotask(async()=>{if(n){await po(e)||await ao(e)}else await ao(e);t()})});mo.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise(t=>{queueMicrotask(async()=>{await ao(e),t()})});mo.set(e,t)}}r.has(n)&&i(`State element with name "${n}" is already registered.`),r.set(n,s),o.debug&&console.debug(`State element registered: name="${n}"`,s)}}const yo=new Map;function No(e,t,n){if(null===n)yo.delete(e);else{yo.set(e,n);const o=n.parseBindTextResult,s=go(t,o.stateName);null===s&&i(`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=go(t,n.stateName);null===e&&i(`State element with name "${n.stateName}" not found for fragment info node.`),e.setPathInfo(n.statePathName,n.bindingType)}}}function So(e){return yo.get(e)||null}const xo=/^@@wcs-(?:for|if|elseif|else):[^-]/,Io=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,_o=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,Po=/^@@wcs-text-start:(.+)$/;class vo extends HTMLElement{_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=r.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 n=o.tagNames.ssr,s=e instanceof Element?e:e instanceof Document?e.documentElement:null;if(!s)return null;return s.querySelector(`${n}[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 n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=JSON.stringify(t),e.appendChild(n);const s=Array.from(yo.keys());for(const t of s){const n=So(t);if(!n)continue;const s=document.createElement("template");s.setAttribute("id",t);const r=n.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(o.bindAttributeName,i);const a=n.fragment.cloneNode(!0);s.content.appendChild(a),e.appendChild(s)}const r=Array.from(gn);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],o=mn(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=JSON.stringify(t),e.appendChild(n)}}gn.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(Io.test(e.data)||_o.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;xo.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=Po.exec(e.data);o&&n.push({comment:e,path:o[1]})}for(const{comment:e,path:t}of n){const n=document.createComment(`@@: ${t}`);e.parentNode.insertBefore(n,e);let o=e.nextSibling;e.remove();const s=`@@wcs-text-end:${t}`;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=e}}}static cleanupDom(e){const t=document.body,n=e.querySelectorAll(o.tagNames.ssr),s=new Map;for(const e of n){const t=e.querySelectorAll("template[id]");for(const e of t){const t=e.getAttribute("id");t&&s.set(t,e)}}const r=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const e=r.currentNode;Io.test(e.data)&&i.push(e)}for(const e of i){const t=Io.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()}vo.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const e=a.currentNode;if(xo.test(e.data)){const t=e.data.split(":")[1];l.push({comment:e,uuid:t})}}for(const{comment:e,uuid:t}of l){const n=s.get(t);if(n){const t=document.createElement("template"),s=n.getAttribute(o.bindAttributeName);s&&t.setAttribute(o.bindAttributeName,s);const r=document.importNode(n.content,!0);if(r.childNodes.length>0)t.content.appendChild(r);else for(const e of Array.from(n.childNodes))t.content.appendChild(document.importNode(e,!0));e.parentNode.replaceChild(t,e)}}const c=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of c)e.removeAttribute("data-wcs-ssr-id");for(const e of n)e.remove()}}async function $o(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 Ao(e){try{return(await import(e)).default||{}}catch(e){i(`Failed to load script file: ${e}`)}}class Co{_loopContextStack=Array(h).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&i("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=h&&i("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&&i("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&&i("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else 1!==n.pathInfo.wildcardCount&&i("Cannot push loop context for a list with wildcard positions when there is no active loop context.");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 Eo=new WeakMap;function ko(e,t){let n=Eo.get(e);void 0===n&&(n=new Map,Eo.set(e,n));let o=n.get(t);return void 0===o&&(o=new be(t),n.set(t,o)),o}const To=new WeakMap;function Mo(e){const t=To.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 ko(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:ko(e,n)}},set(){i("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){i("$command namespace is read-only; deleting from it is not allowed.")}});return To.set(e,n),n}function Oo(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 Lo(e){return function(t){const n=this.stateElement;n&&n.initializePromise.then(()=>{n.createState("writable",n=>{n[e]=t})})}}function Do(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 Wo(e){return e.startsWith("$")}const Ro=new Map;class Fo{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,l="none";const c=[];for(let e=0;e<t.length;e++){const l=t[e];if("*"===l)n[e]="*",c.push(null),s++,a++;else{const t=Number(l);Number.isNaN(t)||(n[e]="*",c.push(t),r++,a++)}i+=l,o.push(i),i+=e<l.length-1?".":""}const d=A(n.join("."));(s>0||r>0)&&(l=s===a?"context":r===a?"all":"partial"),this.path=e,this.segments=t,this.paths=o,this.wildcardCount=a,this.wildcardType=l,this.wildcardIndexes=c,this.pathInfo=d}}function Bo(e){let t;return Ro.get(e)??(Ro.set(e,t=new Fo(e)),t)}const jo=new WeakMap;function qo(e,t){null===t?jo.delete(e):jo.set(e,t)}function zo(e){const t=jo.get(e);t&&(t.dirty=!0)}function Ho(e,t,n,o,s){if(t.pathInfo.segments[0]===x){let e=Mo(s);for(let n=1;n<t.pathInfo.segments.length;n++){if(null==e)return;e=Reflect.get(e,t.pathInfo.segments[n])}return e}if(!(t.pathInfo.path in e)){const s=Vo(e,t.parentAddress??i(`address.parentAddress is undefined path: ${t.pathInfo.path}`),n,o),r=t.pathInfo.segments[t.pathInfo.segments.length-1];if(r===p){const e=t.listIndex?.index??i(`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 Uo(e,t,n,o,s){const r=et(Ke(s,t.pathInfo),t.listIndex),i=function(e){return jo.get(e)??null}(r);if(null!==i&&!1===i.dirty)return i.value;const a=Ho(e,t,n,o,s);return qo(r,{value:a,dirty:!1}),a}function Vo(e,t,n,o){!function(e,t){if(e.addressStackLength>0){const n=e.lastAddressStack?.pathInfo??null,o=e.stateElement;null!==n&&o.getterPaths.has(n.path)&&n.path!==t.pathInfo.path&&o.addDynamicDependency(t.pathInfo.path,n.path)}}(o,t);const s=o.stateElement;return t.pathInfo.wildcardCount>0||s.getterPaths.has(t.pathInfo.path)?Uo(e,t,n,o,s):Ho(e,t,n,o,s)}function Jo(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}const Xo=new class{_queueAbsoluteAddresses=[];constructor(){}enqueueAbsoluteAddress(e){const t=0===this._queueAbsoluteAddresses.length;this._queueAbsoluteAddresses.push(e),t&&queueMicrotask(()=>{const e=this._queueAbsoluteAddresses;this._queueAbsoluteAddresses=[],this._applyChange(e)})}testApplyChange(e){this._applyChange(e)}_applyChange(e){const t=new Set(e),n=[];for(const e of t){const t=Tt(e);for(const e of t)!1!==e.replaceNode.isConnected&&n.push(e)}An(n)}};function Ko(){return Xo}const Yo=new WeakMap;function Go(e,t){null===t?Yo.delete(e):Yo.set(e,t)}function Qo(e,t,n){const s=A(e.wildcardParentPaths[t]),r=Ke(e.stateElement,s),i=me(s,n),a=Ve(et(r,n)),l=e.stateProxy[_e](i),c=function(e,t){switch(t){case"old":return e.oldIndexes;case"new":return e.newIndexes;case"add":return e.addIndexSet;case"change":return e.changeIndexSet;case"delete":return e.deleteIndexSet;default:return o.debug&&console.log(`Invalid search type: ${t}`),[]}}(Et(i.listIndex,a,l),e.searchType);if(t===e.wildcardPaths.length-1)e.targetListIndexes.push(...c);else for(const n of c)Qo(e,t+1,n)}function Zo(e,t,n,o,s,r,a,l,c){const d={stateElement:t,staticMap:o,dynamicMap:s,result:new Set,listPathSet:r,visited:new Set,stateProxy:a,searchType:l};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&&i(`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,a=s+1,l=[],c=e.staticMap.get(r);if(c)for(const n of c){const o=A(n);if(e.listPathSet.has(r)&&o.lastSegment===p){const n=e.stateProxy[_e](t),s=Ve(et(Ke(e.stateElement,t.pathInfo),t.listIndex)),r=Et(t.listIndex,s,n);for(const t of r.newIndexes){const n=me(o,t);e.result.add(n),l.push({address:n,depth:a})}}else{const n=me(o,t.listIndex);e.result.add(n),l.push({address:n,depth:a})}}const d=e.dynamicMap.get(r);if(d)for(const n of d){const o=A(n),s=[];if(o.wildcardCount>0){const n=rt(t.pathInfo,o);if(o.wildcardCount-n>=1){let r;n>0?(null===t.listIndex&&i(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),r=t.listIndex.at(n-1)):r=null;const a={stateElement:e.stateElement,targetListIndexes:[],wildcardPaths:o.wildcardPaths,wildcardParentPaths:o.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};Qo(a,n,r),s.push(...a.targetListIndexes)}else{null===t.listIndex&&i(`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=me(o,t);e.result.add(n),l.push({address:n,depth:a})}}for(let e=l.length-1;e>=0;e--)o.push(l[e])}}(d,n,c),Array.from(d.result)}function es(e,t,n,o,s,r){try{if(!(t.pathInfo.path in e)){const n=Vo(e,t.parentAddress??i(`address.parentAddress is undefined path: ${t.pathInfo.path}`),s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===p){const e=t.listIndex?.index??i(`address.listIndex?.index is undefined path: ${t.pathInfo.path}`);return Reflect.set(n,e,o)}return Reflect.set(n,a,o)}if(!r.stateElement.setterPaths.has(t.pathInfo.path))return Reflect.set(e,t.pathInfo.path,o);r.pushAddress(t);try{return Reflect.set(e,t.pathInfo.path,o,s)}finally{r.popAddress()}}finally{const e=Ko();e.enqueueAbsoluteAddress(n),Zo(r.stateName,r.stateElement,t,r.stateElement.staticDependency,r.stateElement.dynamicDependency,r.stateElement.listPaths,s,"new",n=>{if(n===t)return;const o=et(Ke(r.stateElement,n.pathInfo),n.listIndex);zo(o),e.enqueueAbsoluteAddress(o)})}}function ts(e,t,n,o,s,r){let a=t.parentAddress??i(`address.parentAddress is undefined path: ${t.pathInfo.path}`),l=function(e){return Yo.get(e)??null}(a);if(null===l){const t=Vo(e,a,s,r)??[],n=Pt(t)??[];l={value:[...t],listIndexes:[...n]},Go(a,l)}try{return es(e,t,n,o,s,r)}finally{const n=l.value.indexOf(o),i=Vo(e,a,s,r)??[],c=Array.isArray(i)?Pt(i)??[]:[],d=t.listIndex.index,u=-1!==n?l.listIndexes[n]:It(a.listIndex,-1);c[d]=u;if(new Set(i).size===l.value.length){for(let e=0;e<c.length;e++)c[e].index=e;Go(a,null)}}}function ns(e,t,n,o,s){const r=s.stateElement,i=r.elementPaths.has(t.pathInfo.path),a=t.pathInfo.wildcardCount>0||r.getterPaths.has(t.pathInfo.path),l=et(Ke(r,t.pathInfo),t.listIndex);try{return i?ts(e,t,l,n,o,s):es(e,t,l,n,o,s)}finally{a&&qo(l,{value:n,dirty:!1});const e=r.bindableEventMap[t.pathInfo.path];if(e){const t=r.rootNode;t instanceof ShadowRoot&&t.host.dispatchEvent(new CustomEvent(e,{detail:n,bubbles:!0}))}}}function os(e,t,n,o){return(t,s,r)=>{const a=A(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)}a.wildcardParentPathInfos.length>s.length&&i(`indexes length is insufficient: ${t}`);let l=null;for(let t=0;t<a.wildcardParentPathInfos.length;t++){const r=a.wildcardParentPathInfos[t],c=me(r,l),d=Pt(Vo(e,c,n,o));null==d&&i(`ListIndexes not found: ${r.path}`);l=d[s[t]]??i(`ListIndex not found: ${r.path}`)}const c=me(a,l);if(!(void 0!==r))return Vo(e,c,n,o);ns(e,c,r,n,o)}}const ss=new WeakMap;function rs(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return Jo(o,s.wildcardPaths.at(-1)??i(`lastWildcardPath is null: ${t.pathInfo.path}`))??i(`ListIndex not found: ${t.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<t.pathInfo.wildcardCount;r++){const a=t.pathInfo.wildcardParentPathInfos[r]??i(`wildcardParentPathInfo is null: ${t.pathInfo.path}`);s=(Pt(Vo(e,me(a,s),n,o))??i(`ListIndex not found: ${a.path}`))[t.wildcardIndexes[r]??i(`wildcardIndex is null: ${t.pathInfo.path}`)]??i(`ListIndex not found: ${a.path}`)}return s}case"partial":i(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function is(e,t,n){void 0!==e.loopContext&&i("already in loop context"),e.setLoopContext(t);try{e.pushAddress(t);try{return n()}finally{e.popAddress()}}finally{e.clearLoopContext()}}function as(e,t,n,o){const s=g[t];if(void 0!==s){0===o.addressStackLength&&i(`No active state reference to get list index for "${t.toString()}".`);const e=o.lastAddressStack?.listIndex;return e?.indexes[s]??i(`ListIndex not found: ${t.toString()}`)}if("string"==typeof t){if("$"!==t[0]){const s=Bo(t),r=rs(e,s,n,o),i=me(s.pathInfo,r);return Vo(e,i,n,o)}switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>function(e,t,n,o){const s=os(e,0,n,o);return(t,r)=>{const a=new Map,l=A(t);if(o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==l.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(l.path,e.path)}if(void 0===r){for(let e=0;e<l.wildcardParentPathInfos.length;e++){const t=l.wildcardParentPathInfos[e],n=Jo(o,t.path);if(n){r=n.indexes;break}}void 0===r&&(r=[])}const c=(t,s,r,l,d,u,f)=>{const p=t[s]??null;if(null===p)return void f.push(u);const h=me(p,r),m=ss.get(h),g=Vo(e,h,n,o),b=Et(r,m,g).newIndexes,w=l[d]??null;if(a.set(h,g),null===w)for(let e=0;e<b.length;e++){const n=b[e];c(t,s+1,n,l,d+1,u.concat(n.index),f)}else{const e=b[w]??i(`ListIndex not found: ${p.path}`);s+1<t.length?c(t,s+1,e,l,d+1,u.concat(e.index),f):f.push(u.concat(e.index))}},d=[];c(l.wildcardParentPathInfos,0,null,r,0,[],d);const u=[];for(let e=0;e<d.length;e++)u.push(s(l.path,d[e]));for(const[e,t]of a.entries())ss.set(e,t);return u}}(e,0,n,o)(t,s);case"$postUpdate":return t=>function(e,t,n,o){const s=o.stateElement;return t=>{const r=Bo(t),i=rs(e,r,n,o),a=me(r.pathInfo,i),l=et(Ke(s,a.pathInfo),a.listIndex),c=Ko();c.enqueueAbsoluteAddress(l),Zo(o.stateName,o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=et(Ke(s,e.pathInfo),e.listIndex);zo(t),c.enqueueAbsoluteAddress(t)})}}(e,0,n,o)(t);case"$resolve":return(t,s,r)=>os(e,0,n,o)(t,s,r);case"$trackDependency":return e=>function(e,t,n,o){return e=>{0===o.addressStackLength&&i(`No active state reference to track dependency for path "${e}".`);const t=o.lastAddressStack?.pathInfo??i("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 x:return Mo(o.stateElement)}}else if("symbol"==typeof t){switch(t){case xe:return(e,t=async()=>{})=>async function(e,t,n){return await is(e,t,n)}(o,e,t);case Ie:return(e,t=()=>{})=>function(e,t,n){return is(e,t,n)}(o,e,t);case _e:return t=>Vo(e,t,n,o);case Pe:return(t,s)=>ns(e,t,s,n,o);case ve:return()=>async function(e,t,n){const o=Reflect.get(e,b);"function"==typeof o&&await o.call(n)}(e,0,n);case $e:return()=>function(e,t,n){const o=Reflect.get(e,w);"function"==typeof o&&o.call(n)}(e,0,n);case Ae:return t=>function(e,t,n,o){const s=Reflect.get(e,"$updatedCallback");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 ls{_stateElement;_stateName;_addressStack=Array(h).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;constructor(e,t,n){this._stateName=t;const o=go(e,this._stateName);null===o&&i(`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&&i("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex++,this._addressStackIndex>=h&&i("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&&i(`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 as(e,t,n,this)}set(e,t,n,o){return"readonly"===this._mutability&&i(`State "${this._stateName}" is readonly.`),function(e,t,n,o,s){if("string"==typeof t){const r=Bo(t),i=rs(e,r,o,s);return ns(e,me(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 cs=new WeakMap;const ds=new WeakMap;function us(e,t){const n=ds.get(e);return n?n.get(t)??null:null}const fs=new WeakMap,ps=new WeakMap,hs=new WeakMap,ms=new WeakMap;function gs(e,t){return{innerAbsPathInfo:Ke(e,A(t.propSegments.slice(1).join(f))),outerAbsPathInfo:ct(t).absolutePathInfo}}function bs(e,t){let n=fs.get(e);if(void 0===n&&(n=new Map,fs.set(e,n)),n.has(t))return n.get(t);let o=ps.get(e);void 0===o&&(o=new Map,ps.set(e,o));const s=hs.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&&i("Duplicate mapping rule for web component."),r=e;break}if(null===r)return null;const a=ms.get(r);void 0===a&&i("Binding not found for primary mapping rule on web component.");const l=t.pathInfo.segments.slice(r.innerAbsPathInfo.pathInfo.segments.length),c=A(r.outerAbsPathInfo.pathInfo.segments.concat(l).join(f)),d=go(e.getRootNode(),a.stateName);null===d&&i(`State element with name "${a.stateName}" not found for web component.`);const u=Ke(d,c);n.set(t,u),o.set(u,t);return function(e,t){const n=W(e);null===n?R(e,[t]):n.push(t)}(e,{...a,propName:t.pathInfo.path,propSegments:t.pathInfo.segments,statePathName:u.pathInfo.path,statePathInfo:u.pathInfo}),u}function ws(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 ys{_webComponent;_innerStateElement;constructor(e,t){this._webComponent=e,this._innerStateElement=us(e,t)??i("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=A(t),s=Ke(this._innerStateElement,o),r=bs(this._webComponent,s);if(null!==r){const e=Ne(this._webComponent);let t;return r.stateElement.createState("readonly",n=>{n[Ie](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){cs.set(e,t)}(et(r,o),t)})}),t}if(t in e)return Reflect.get(e,t,n);i(`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=A(t),r=Ke(this._innerStateElement,s),a=bs(this._webComponent,r);if(null!==a){const e=Ne(this._webComponent);return a.stateElement.createState("writable",t=>{t[Ie](e,()=>{t[a.pathInfo.path]=n})}),!0}if(t in e)return Reflect.set(e,t,n,o);i(`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=A(t),o=Ke(this._innerStateElement,n);return null!==bs(this._webComponent,o)||t in e}return Reflect.has(e,t)}}class Ns{_innerStateElement;constructor(e,t){this._innerStateElement=us(e,t)??i("State element not found for web component.")}get(e,t,n){if("string"==typeof t){const e=A(t),n=et(Ke(this._innerStateElement,e),null);return o=n,cs.get(o)}return Reflect.get(e,t,n);var o}set(e,t,n,o){if("string"==typeof t){const e=A(t),n=Ke(this._innerStateElement,e);return this._innerStateElement.createState("readonly",e=>{e.$postUpdate(n.pathInfo.path)}),!0}return Reflect.set(e,t,n,o)}}class Ss{_innerStateElement;constructor(e,t){this._innerStateElement=us(e,t)??i("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 xs=e=>()=>e;function Is(e,t,n,s){if(function(e,t,n){let o=ds.get(e);o||(o=new Map,ds.set(e,o)),o.set(t,n)}(t,n,e),t.hasAttribute(o.bindAttributeName)){const o=(W(t)??[]).filter(e=>e.propSegments[0]===n);!function(e,t,n){if(0===n.length)return;const o=us(e,t);null===o&&i("State element not found for web component.");const s=new Map,r=new Map;for(const t of n){const n=gs(o,t);let i=hs.get(e);void 0===i?hs.set(e,new Set([n])):i.add(n);const a=n.innerAbsPathInfo,l=n.outerAbsPathInfo;ms.set(n,t),s.set(a,l),r.set(l,a)}fs.set(e,s),ps.set(e,r)}(t,n,o);const s=function(e,t){const n=new Ns(e,t);return new Proxy({},n)}(t,n),r=function(e,t){const n=new ys(e,t),o=us(e,t);null===o&&i("State element not found for web component."),null===o.boundComponentStateProp&&i("State element is not bound to any component state prop."),o.boundComponentStateProp in e||i(`State element is not bound to a valid component state prop: ${o.boundComponentStateProp}`);const s=e[o.boundComponentStateProp];return"object"==typeof s&&null!==s||i(`Invalid state object for component state prop: ${o.boundComponentStateProp}`),new Proxy(ws(s),n)}(t,n);e.setInitialState(r),Object.defineProperty(t,n,{get:xs(s),enumerable:!0,configurable:!0})}else{e.setInitialState(ws(s));const o=function(e,t){const n=new Ss(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:xs(o),enumerable:!0,configurable:!0})}if(function(e,t){let n=ut.get(e);n||(n=new WeakMap,ut.set(e,n)),n.set(t,!0)}(t,e),y in t){const e=t[y];"function"==typeof e?e.call(t,n).catch(e=>{i(`Error in ${y}: ${e instanceof Error?e.message:String(e)}`)}):i(`${y} is not a function.`)}}function _s(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 Ps extends HTMLElement{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return bo(e)}__state;_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 Co}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;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&&i(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){this._commandTokenNames=function(e){const t=new Set,n=e[S];if(void 0===n)return t;Array.isArray(n)||i(`${S} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||i(`${S} entries must be non-empty strings.`),e===x&&i(`${S} entry "${e}" conflicts with the reserved namespace name "${x}".`),t.has(e)&&i(`${S} entry "${e}" is duplicated.`),t.add(e);return t}(e),this._eventTokenNames=function(e){const t=new Set,n=e[I];if(void 0===n)return t;Array.isArray(n)||i(`${I} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||i(`${I} entries must be non-empty strings.`),t.has(e)&&i(`${I} entry "${e}" is duplicated.`),t.add(e);return t}(e),this.__state=e,De(this),function(e,t,n){const o=t[_];if(void 0!==o){"object"==typeof o&&null!==o||i(`${_} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||i(`${_} entry "${t}" is not declared in $eventTokens.`),"function"!=typeof s&&i(`${_} entry "${t}" must be a function.`),Le(e,t).subscribe(s)}}(this,e,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._pathSet.clear();const t=_s(e);for(const e of t.getterPaths)this._getterPaths.add(e);for(const e of t.setterPaths)this._setterPaths.add(e);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=vo.findByName(t,e);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null}async _initialize(){const e=t()?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){i("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||i(`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 Ao(e):i(`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 $o(e,`${this._name}`);else{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element with name="${this._name}".`)},6e4);this._state=await this._setStatePromise,clearTimeout(e)}}}catch(e){i(`Failed to initialize state: ${e}`)}if(null!==e&&this.__state)for(const[t,n]of Object.entries(e)){if(t in this.__state){const e=Object.getOwnPropertyDescriptor(this.__state,t);if(e&&(e.get||e.set))continue;if("function"==typeof this.__state[t])continue}this.__state[t]=n}await this._loadingPromise,this._name=this.getAttribute("name")||"default",wo(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,n=t?k(t):null;null!==t&&null!==n||i(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),e instanceof ShadowRoot||this.hasAttribute("name")||i('"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(n.toLowerCase()),t.hasAttribute(o.bindAttributeName)&&await d(t),s in t||i(`Component does not have property "${s}" for state binding.`);const r=t[s];"object"==typeof r&&null!==r||i(`Component property "${s}" is not an object for state binding.`),this._boundComponent=t,this._boundComponentStateProp=s,Is(this,this._boundComponent,this._boundComponentStateProp,r)}}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{b in e&&await e[ve]()})}async _initializeDCC(e,t){let n;try{if(this.hasAttribute("src")){const e=this.getAttribute("src");e.endsWith(".js")?n=await Ao(e):i(`DCC: Unsupported src type: ${e}`)}else{const t=this.querySelector('script[type="module"]');t?n=await $o(t,e.tagName.toLowerCase()):i(`DCC: No state source found for "${e.tagName.toLowerCase()}".`)}}catch(e){i(`DCC: Failed to load state: ${e}`)}!function(e,t,n){const s=e.tagName.toLowerCase();if(s.includes("-")||i(`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 a=t.mode,l=Array.isArray(n[N])?n[N]:[],c=l.length>0?function(e,t){return{protocol:"wc-bindable",version:1,properties:t.map(t=>({name:t,event:`${e}:${t}-changed`}))}}(s,l):null,d=l.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(s,l):{},u=`${o.tagNames.state}:not([name])`,f=class extends HTMLElement{static template=r;static shadowRootMode=a;static wcBindable=c;static bindableEventMap=d;_shadow=null;connectedCallback(){if(!this.hasAttribute(P)&&(this._shadow=this.attachShadow({mode:f.shadowRootMode}),this._shadow.appendChild(f.template.content.cloneNode(!0)),Object.keys(f.bindableEventMap).length>0)){const e=this._shadow.querySelector(u);e&&e.initializePromise.then(()=>{e.setBindableEventMap(f.bindableEventMap)})}}get stateElement(){return this._shadow?.querySelector(u)}},p=Object.getOwnPropertyDescriptors(n);for(const[e,t]of Object.entries(p)){if(Wo(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=Do(e,o)}else n.get=Oo(e),n.set=Lo(e);Object.defineProperty(f.prototype,e,n)}customElements.define(s,f)}(e,t,n),this._initialized=!0,this._rootNode=null,this._resolveInitialize?.(),this._resolveConnectedCallback?.()}_callStateDisconnectedCallback(){this.createState("writable",e=>{w in e&&e[$e]()})}async connectedCallback(){if(this._rootNode=this.getRootNode(),!this._initialized){const e=this.parentNode;if(e instanceof ShadowRoot&&e.host.hasAttribute(P))return void await this._initializeDCC(e.host,e);await this._initializeBindWebComponent(),await this._initialize(),this._initialized=!0,this._resolveInitialize?.()}if(this.hasAttribute("enable-ssr")&&!t()||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr")){await bo(this.rootNode);const e=this.getAttribute("name")||"default",t=vo.extractStateData(this),n=document.createElement(o.tagNames.ssr);n.setAttribute("name",e),n.setAttribute("version",r),vo.buildContent(n,t),this.parentNode?.insertBefore(n,this)}this._resolveConnectedCallback?.()}disconnectedCallback(){var e;null!==this._rootNode&&(this._callStateDisconnectedCallback(),wo(this.rootNode,this._name,null),e=this,Eo.delete(e),function(e){To.delete(e)}(this),De(this),this._rootNode=null)}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&&i("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+"."+p)),!this._pathSet.has(e)){const t=A(e);if(this._pathSet.add(e),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=A(e.parentPath)}}}_createState(e,t,n){try{const o=function(e,t,n,o){const s=new ls(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}bindProperty(e,t){Object.defineProperty(this._state,e,t)}setInitialState(e){this._initialized?this._state=e:this._resolveSetState?.(e)}}function vs(){customElements.get(o.tagNames.ssr)||customElements.define(o.tagNames.ssr,vo),customElements.get(o.tagNames.state)||customElements.define(o.tagNames.state,Ps)}function $s(e){var t;e&&((t=e).tagNames&&Object.assign(n.tagNames,t.tagNames),"string"==typeof t.bindAttributeName&&(n.bindAttributeName=t.bindAttributeName),"string"==typeof t.commentTextPrefix&&(n.commentTextPrefix=t.commentTextPrefix),"string"==typeof t.commentForPrefix&&(n.commentForPrefix=t.commentForPrefix),"string"==typeof t.commentIfPrefix&&(n.commentIfPrefix=t.commentIfPrefix),"string"==typeof t.commentElseIfPrefix&&(n.commentElseIfPrefix=t.commentElseIfPrefix),"string"==typeof t.commentElsePrefix&&(n.commentElsePrefix=t.commentElsePrefix),"string"==typeof t.locale&&(n.locale=t.locale),"boolean"==typeof t.debug&&(n.debug=t.debug),"boolean"==typeof t.enableMustache&&(n.enableMustache=t.enableMustache)),vs()}function As(e){return e}export{vo as Ssr,r as VERSION,$s as bootstrapState,ao as buildBindings,As as defineState,bo as getBindingsReady,s as getConfig};
1
+ let e=null;function t(){if(null!==e)return e;const t=document.querySelector("html");return e=!!t&&t.hasAttribute("data-wcs-server"),e}const n={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,sameValueGuard:!0},s=n;function o(){return s}const r="1.16.0";function i(e){throw new Error(`[@wcstack/state] ${e}`)}const a=new WeakMap;let c=0;function l(e){let t,n=a.get(e)||null;if(null!==n)return n;const s=new Promise(e=>{t=e});return n={id:++c,promise:s,resolve:t},a.set(e,n),n}async function d(e){const t=l(e);await t.promise}function u(e){const t=e.node,n=e.replaceNode;t!==n&&null!==t.parentNode&&t.parentNode.replaceChild(n,t)}const f=".",p="*",h=128,m="|",g={};for(let e=0;e<128;e++)g[`$${e+1}`]=e;const b=Object.freeze(g),y="$connectedCallback",w="$disconnectedCallback",N="$updatedCallback",x="$stateReadyCallback",S="$bindables",A="$commandTokens",I="$command",_="$eventTokens",v="$on",P="data-wc-definition",T=new Map;let $=0;function C(e){let t=T.get(e);return void 0!==t||(t=Object.freeze(new E(e)),T.set(e,t)),t}class E{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:C(t),n=e.split("."),s=[],o=[],r=[],i={},a=[],c=[],l=[],d=[];let u="",f="",h=0;for(let e=0;e<n.length;e++)u+=n[e],n[e]===p&&(r.push(u),i[u]=h,a.push(t(u)),c.push(f),l.push(t(f)),d.push(e),h++),s.push(u),o.push(t(u)),f=u,u+=".";const m=r.length>0?r[r.length-1]:null,g=s.length>1?s[s.length-2]:null;this.path=e,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=s,this.cumulativePathSet=new Set(s),this.cumulativePathInfos=o,this.cumulativePathInfoSet=new Set(o),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=l,this.wildcardParentPathInfoSet=new Set(l),this.wildcardPositions=d,this.lastWildcardPath=m,this.lastWildcardInfo=m?t(m):null,this.parentPath=g,this.parentPathInfo=g?t(g):null,this.wildcardCount=h}}const k=new WeakMap;function M(e){const t=k.get(e);if(void 0!==t)return t;let n=null;try{if(e.nodeType!==Node.ELEMENT_NODE)return n;const t=e,s=t.tagName.toLowerCase();if(s.includes("-"))return n=s;if(t.hasAttribute("is")){const e=t.getAttribute("is");if(e.includes("-"))return n=e}return n}finally{k.set(e,n)}}function O(e){if("object"!=typeof e||null===e)return!1;const t=e;return"wc-bindable"===t.protocol&&1===t.version&&Array.isArray(t.properties)}function D(e,t,n){const s="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:s,statePathInfo:C(s),stateName:n,inFilters:[],outFilters:[],bindingType:"prop"}}function L(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function W(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 R=new WeakMap;function F(e){return R.get(e)||null}function B(e,t){R.set(e,t)}const j=new Set(["if","elseif","else","for"]);function q(e){i(`filter ${e} requires at least one option`)}function z(e){i(`filter ${e} requires a number as option`)}function H(e){i(`filter ${e} requires a number value`)}function V(e){i(`filter ${e} requires a date value`)}function U(e){return!(!e||isNaN(Number(e)))}const J={eq:e=>{const t=e?.[0]??q("eq");return e=>"number"==typeof e?(U(t)||z("eq"),e===Number(t)):e===t},ne:e=>{const t=e?.[0]??q("ne");return e=>"number"==typeof e?(U(t)||z("ne"),e!==Number(t)):e!==t},not:e=>e=>("boolean"!=typeof e&&i(`filter ${"not"} requires a boolean value`),!e),lt:e=>{const t=e?.[0]??q("lt");return U(t)||z("lt"),e=>("number"!=typeof e&&H("lt"),e<Number(t))},le:e=>{const t=e?.[0]??q("le");return U(t)||z("le"),e=>("number"!=typeof e&&H("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??q("gt");return U(t)||z("gt"),e=>("number"!=typeof e&&H("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??q("ge");return U(t)||z("ge"),e=>("number"!=typeof e&&H("ge"),e>=Number(t))},inc:e=>{const t=e?.[0]??q("inc");return U(t)||z("inc"),e=>("number"!=typeof e&&H("inc"),e+Number(t))},dec:e=>{const t=e?.[0]??q("dec");return U(t)||z("dec"),e=>("number"!=typeof e&&H("dec"),e-Number(t))},mul:e=>{const t=e?.[0]??q("mul");return U(t)||z("mul"),e=>("number"!=typeof e&&H("mul"),e*Number(t))},div:e=>{const t=e?.[0]??q("div");return U(t)||z("div"),e=>("number"!=typeof e&&H("div"),e/Number(t))},mod:e=>{const t=e?.[0]??q("mod");return U(t)||z("mod"),e=>("number"!=typeof e&&H("mod"),e%Number(t))},fix:e=>{const t=e?.[0]??"0";return U(t)||z("fix"),e=>("number"!=typeof e&&H("fix"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0]??s.locale;return e=>("number"!=typeof e&&H("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]??q("slice");U(n)||z("slice"),t.push(Number(n));const s=e?.[1];return void 0!==s&&(U(s)||z("slice"),t.push(Number(s))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??q("substr");U(t)||z("substr");const n=e?.[1]??q("substr");return U(n)||z("substr"),e=>String(e).substr(Number(t),Number(n))},pad:e=>{const t=e?.[0]??q("pad");U(t)||z("pad");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},rep:e=>{const t=e?.[0]??q("rep");return U(t)||z("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 U(t)||z("round"),e=>{"number"!=typeof e&&H("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return U(t)||z("floor"),e=>{"number"!=typeof e&&H("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return U(t)||z("ceil"),e=>{"number"!=typeof e&&H("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return U(t)||z("percent"),e=>("number"!=typeof e&&H("percent"),`${(100*e).toFixed(Number(t))}%`)},date:e=>{const t=e?.[0]??s.locale;return e=>(e instanceof Date||V("date"),e.toLocaleDateString(t))},time:e=>{const t=e?.[0]??s.locale;return e=>(e instanceof Date||V("time"),e.toLocaleTimeString(t))},datetime:e=>{const t=e?.[0]??s.locale;return e=>(e instanceof Date||V("datetime"),e.toLocaleString(t))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||V("ymd");const n=e.getFullYear().toString(),s=(e.getMonth()+1).toString().padStart(2,"0"),o=e.getDate().toString().padStart(2,"0");return`${n}${t}${s}${t}${o}`}},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]??q("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},Y=J,G={input:J,output:Y},X=(e,t)=>n=>{const s=n[e];return s||i(`filter not found: ${e}`),s(t)};const K=new Map;function Q(e,t){const n=G[t];return e.map(e=>{const s=e.indexOf("("),o=e.lastIndexOf(")");if(-1!==s&&-1===o&&i(`Invalid filter format: missing closing parenthesis in "${e}"`),-1!==o&&-1===s&&i(`Invalid filter format: missing opening parenthesis in "${e}"`),-1===s){const s=e.trim(),o=`${s}():${t}`;let r=K.get(o);return void 0===r&&(r=X(s,[])(n),K.set(o,r)),{filterName:s,args:[],filterFn:r}}{const r=e.substring(s+1,o),i=e.substring(0,s).trim(),a=function(e){const t=[];let n="",s=null,o=!1;for(let r=0;r<e.length;r++){const i=e[r];s?i===s?s=null:n+=i:'"'===i||"'"===i?(s=i,o=!0):","===i?(t.push(n.trim()),n="",o=!1):n+=i}const r=n.trim();return(r||o)&&t.push(r),t}(r),c=`${i}(${a.join(",")}):${t}`;let l=K.get(c);return void 0===l&&(l=X(i,a)(n),K.set(c,l)),{filterName:i,args:a,filterFn:l}}})}const Z=e=>e.trim(),ee=new Map;const te=new Map;function ne(e){const t=e.indexOf(m);let n="",s=[],o="",r=[];-1!==t?(n=e.slice(0,t).trim(),o=e.slice(t+1).trim(),te.has(o)?r=te.get(o):(s=o.split(m).map(Z),r=Q(s,"output"),te.set(o,r))):n=e.trim();const[i,a="default"]=n.split("@").map(Z);return{stateName:a,statePathName:i,statePathInfo:C(i),outFilters:r}}function se(e){const[...t]=e.split(";").map(Z).filter(e=>e.length>0),n=t.map(e=>{const t=e.indexOf(":");-1===t&&i(`Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.`);const n=e.slice(0,t).trim(),s=e.slice(t+1).trim();if("else"===n){return{propName:"else",propSegments:["else"],propModifiers:[],statePathName:"#else",statePathInfo:C("#else"),stateName:"",inFilters:[],outFilters:[],bindingType:"else"}}if("..."===n){const t=ne(s);return t.outFilters.length>0&&i(`Invalid spread binding "${e}": filters are not allowed on spread targets.`),0===t.statePathName.length&&i(`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:[],...ne(s),bindingType:n}}{const e=ne(s),t=function(e){const t=e.indexOf(m);let n="",s=[],o="",r=[];-1!==t?(n=e.slice(0,t).trim(),o=e.slice(t+1).trim(),ee.has(o)?r=ee.get(o):(s=o.split(m).map(Z),r=Q(s,"input"),ee.set(o,r))):n=e.trim();const[i,a]=n.split("#").map(Z),c=i.split(f).map(Z);return{propName:i,propSegments:c,propModifiers:a?a.split(",").map(Z):[],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=>j.has(e.bindingType))&&i(`Invalid bindText: "${e}". 'if', 'elseif', 'else', and 'for' bindings must be single binding.`)}return n}const oe=new WeakMap,re=new Set([s.commentTextPrefix,s.commentForPrefix,s.commentIfPrefix,s.commentElseIfPrefix,s.commentElsePrefix]),ie=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function ae(e){const t=oe.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),o=ie.exec(n);if(null===o)return null;const r=o[1]||s.commentTextPrefix;return re.has(r)?(oe.set(e,o[2]),o[2]):null}function ce(e){if(e.nodeType===Node.ELEMENT_NODE){return se(e.getAttribute(s.bindAttributeName)||"")}if(e.nodeType===Node.COMMENT_NODE){const t=ae(e);null===t&&i("Comment node binding text not found.");const n=Ss(t);let s=n?.parseBindTextResult??null,o=null;return null===s?(s={propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...ne(t),bindingType:"text"},o=null):o=t,[{...s,uuid:o}]}return[]}function le(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(e){if(e.nodeType===Node.ELEMENT_NODE){return e.hasAttribute(s.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==ae(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}const de=new WeakSet;function ue(e,t,n){const o=function(e,t,n={}){const o=n.allowDeferred??!0;if(!t.some(e=>"spread"===e.bindingType))return t;const r=[],a=new WeakSet;for(const n of t){if("spread"!==n.bindingType){r.push(n);continue}e.nodeType!==Node.ELEMENT_NODE&&i("Spread binding requires an element node.");const t=e,s=M(t);null===s&&i(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const c=customElements.get(s);if(void 0===c){o||i(`Spread binding "${n.statePathName}" requires <${s}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}const l=c.wcBindable;O(l)||i(`Spread binding "${n.statePathName}" requires <${s}> to declare wcBindable (protocol="wc-bindable", version=1).`);const d=n.statePathName,u=n.stateName,f=new Set;for(const e of l.properties){if(f.has(e.name))continue;f.add(e.name);const t=D(e.name,d,u);a.add(t),r.push(t)}for(const e of l.inputs??[]){if(f.has(e.name))continue;f.add(e.name);const t=D(e.name,d,u);a.add(t),r.push(t)}}const c=new Map;for(let e=0;e<r.length;e++){const t=L(r[e]);null!==t&&c.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=L(r[t]);if(null!==n){if(c.get(n)===t)l.push(r[t]);else if(s.debug&&a.has(r[t])){const s=r[c.get(n)],o=e.nodeType===Node.ELEMENT_NODE?`<${e.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[t].propName}" of ${o} overridden by explicit binding (statePath: "${s.statePathName}").`)}}else l.push(r[t])}return l}(e,t,{allowDeferred:n.allowDeferred});if(o.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?M(e):null;return null===n&&i("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t}}}de.add(e);const r=function(e,t){const n=[];for(const s of t)if("text"!==s.bindingType)n.push({...s,node:e,replaceNode:e});else{const t=document.createTextNode("");n.push({...s,node:e,replaceNode:t})}return n}(e,o);return B(e,r),function(e){l(e).resolve()}(e),{bindings:r,deferred:null}}function fe(e){const t=le(e),n=[],s=[];for(const e of t){if(de.has(e))continue;const t=ue(e,ce(e),{allowDeferred:!0});null===t.deferred?n.push(...t.bindings):s.push(t.deferred)}return[t,n,s]}function pe(e){const{node:t,parseResults:n}=e;!function(e){de.delete(e)}(t);return ue(t,n,{allowDeferred:!1}).bindings}const he=new WeakMap,me=new WeakMap;class ge{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]===p?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=be(e,t)}}function be(e,t){if(null===t){let t=me.get(e);return void 0!==t||(t=new ge(e,null),me.set(e,t)),t}{let n=he.get(t);void 0===n&&(n=new WeakMap,he.set(t,n));let s=n.get(e);return void 0!==s||(s=new ge(e,t),n.set(e,s)),s}}class ye{_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 we extends ye{}function Ne(e){return e instanceof we}const xe=new WeakMap;function Se(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 Ie=Symbol("$$setLoopContextAsync"),_e=Symbol("$$setLoopContext"),ve=Symbol("$$getByAddress"),Pe=Symbol("$$setByAddress"),Te=Symbol("$$connectedCallback"),$e=Symbol("$$disconnectedCallback"),Ce=Symbol("$$updatedCallback");const Ee=new Map,ke=new Map;const Me=(e,t,n,s)=>o=>{n.includes("prevent")&&o.preventDefault(),n.includes("stop")&&o.stopPropagation();const r=o.target,a=bs(r.getRootNode(),e);null===a&&i(`State element with name "${e}" not found for event handler.`);const c=Se(r),l=t.startsWith(I+".");a.createStateAsync("writable",async n=>{n[_e](c,()=>{const r=c?.listIndex.indexes??[];if(l){const e=n[ve](be(s,null));return Ne(e)||i(`Event binding "${t}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),e.emit(o,...r)}const a=n[t];return"function"!=typeof a&&i(`Handler "${t}" is not a function on state "${e}".`),Reflect.apply(a,n,[o,...r])})})};function Oe(e){if(!e.propName.startsWith("on"))return!1;const t=function(e){const t=e.propModifiers.filter(e=>"prevent"===e||"stop"===e).sort().join(",");return`${e.stateName}::${e.statePathName}::${t}`}(e);let n=Ee.get(t);void 0===n&&(n=Me(e.stateName,e.statePathName,e.propModifiers,e.statePathInfo),Ee.set(t,n));const s=e.propName.slice(2);e.node.addEventListener(s,n);let o=ke.get(t);return void 0===o?(o=new Set([e]),ke.set(t,o)):o.add(e),!0}class De extends ye{}const Le=new WeakMap;function We(e,t){let n=Le.get(e);void 0===n&&(n=new Map,Le.set(e,n));let s=n.get(t);return void 0===s&&(s=new De(t),n.set(t,s)),s}function Re(e){Le.delete(e)}const Fe=new WeakMap;function Be(e){if("eventToken"!==e.propSegments[0])return!1;const t=e.node,n=M(t);if(null!==n&&void 0===customElements.get(n))return customElements.whenDefined(n).then(()=>{Be(e)}),!0;if(Fe.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||i('eventToken binding requires a property name (e.g., "eventToken.error").');const o=function(e){const t=M(e);if(null===t)return null;const n=customElements.get(t),s=n?.wcBindable;return"wc-bindable"===s?.protocol&&1===s?.version?s:null}(t);null===o&&i(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const r=o.properties.find(e=>e.name===s);void 0===r&&i(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.`);const a=r.event,c=e.statePathName,l=e.stateName,d=e.propModifiers,u=e=>{d.includes("prevent")&&e.preventDefault(),d.includes("stop")&&e.stopPropagation();const n=bs(t.getRootNode(),l);null===n&&i(`State element with name "${l}" not found for eventToken handler.`),n.eventTokenNames.has(c)||i(`eventToken "${c}" is not declared in $eventTokens of state "${l}".`);const s=Se(t);n.createStateAsync("writable",async t=>{t[_e](s,()=>{const o=s?.listIndex.indexes??[];return We(n,c).emit(t,e,...o)})})};return t.addEventListener(a,u),Fe.set(e,{eventName:a,handler:u}),!0}const je=new Set(["radio","checkbox"]),qe=new Set(["value","valueAsNumber","valueAsDate"]);const ze=new Map,He=new Map,Ve=e=>e.detail;function Ue(e){const t=M(e.node);if(null!==t){if(void 0===customElements.get(t))return void customElements.whenDefined(t).then(()=>{Ue(e)})}if(function(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return!1;const n=e,s=n.tagName.toLowerCase();if("input"===s){const e=(n.getAttribute("type")||"text").toLowerCase();if("button"===e)return!1;if(je.has(e)&&"checked"===t)return!0;if(qe.has(t))return!0}if("select"===s&&"value"===t)return!0;if("textarea"===s&&"value"===t)return!0;const o=M(n);if(null!==o){const e=customElements.get(o);void 0===e&&i(`Custom element <${o}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const n=e.wcBindable;if("wc-bindable"===n?.protocol&&1===n?.version&&n.properties.some(e=>e.name===t))return!0}return!1}(e.node,e.propName)&&-1===e.propModifiers.indexOf("ro")){const t=function(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=M(e.node);if(null!==n){const s=customElements.get(n);void 0===s&&i(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const o=s.wcBindable;if("wc-bindable"===o?.protocol&&1===o?.version){const n=o.properties.find(t=>t.name===e.propName);n&&(t=n.event)}}for(const n of e.propModifiers)n.startsWith("on")&&(t=n.slice(2));return t}(e),n=function(e){const t=M(e.node);if(null!==t){const n=customElements.get(t);if(n){const t=n.wcBindable;if("wc-bindable"===t?.protocol&&1===t?.version){const n=t.properties.find(t=>t.name===e.propName);if(n)return n.getter??Ve}}}return null}(e),s=function(e,t,n){const s=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.stateName}::${e.propName}::${e.statePathName}::${t}::${s}::${n?"g":"n"}`}(e,t,null!==n);let o=ze.get(s);void 0===o&&(o=((e,t,n,s,o)=>r=>{const a=r.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let c;if(null!==o)c=o(r);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=bs(a.getRootNode(),e);null===d&&i(`State element with name "${e}" not found for two-way binding.`);const u=Se(a);d.createState("writable",e=>{e[_e](u,()=>{e[n]=l})})})(e.stateName,e.propName,e.statePathName,e.inFilters,n),ze.set(s,o)),e.node.addEventListener(t,o);let r=He.get(s);void 0===r?(r=new Set([e]),He.set(s,r)):r.add(e)}}const Je=new WeakMap;function Ye(e){return Je.get(e)??[]}function Ge(e,t){Je.set(e,t)}const Xe=new WeakMap;function Ke(e,t){if(Xe.has(e)){const n=Xe.get(e);if(n.has(t))return n.get(t)}else Xe.set(e,new WeakMap);const n=Object.freeze(new Qe(e,t));return Xe.get(e).set(t,n),n}class Qe{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=Ke(e,t.parentPathInfo)}}const Ze=new WeakMap,et=new WeakMap;class tt{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]===p?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAbsoluteAddress=nt(e,t)}}function nt(e,t){if(null===t){let t=et.get(e);return void 0!==t||(t=new tt(e,null),et.set(e,t)),t}{let n=Ze.get(t);void 0===n&&(n=new WeakMap,Ze.set(t,n));let s=n.get(e);return void 0!==s||(s=new tt(e,t),n.set(e,s)),s}}const st=new WeakMap;function ot(e,t){null===t?st.delete(e):st.set(e,t)}function rt(e){return st.get(e)||null}const it=new Map;function at(e,t){let n,s;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,s=t):(n=t,s=e);const o=`${n.path}\t${s.path}`;let r=it.get(o);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(s.wildcardPathSet).size,it.set(o,r),r}const ct=new WeakMap;function lt(e){const t=Se(e.node);if(null===t)return null;let n=ct.get(t);if(void 0===n)n=new WeakMap,ct.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let s=null;try{const n=at(t.pathInfo,e.statePathInfo);return n>0&&(s=t.listIndex.at(n-1)),s}finally{n.set(e,s)}}const dt=new WeakMap;function ut(e){let t=null;if(t=dt.get(e)||null,null!==t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=rt(n);null===t?i(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}const s=lt(e),o=bs(n,e.stateName);null===o&&i(`State element with name "${e.stateName}" not found for binding.`);return t=nt(Ke(o,e.statePathInfo),s),dt.set(e,t),t}function ft(e){dt.delete(e)}const pt=new WeakMap;function ht(e,t){const n=pt.get(e);return!!n&&!0===n.get(t)}function mt(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const gt=Object.freeze([]);const bt=new WeakMap;const yt=new WeakMap;function wt(e){return yt.get(e)??[]}function Nt(e,t){yt.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 xt=0;function St(){return`u${(xt++).toString(36)}`}let At=0;class It{uuid=St();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=At}get index(){return this._index}set index(e){this._index=e,this._version=++At,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=At),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 _t(e,t){return new It(e,t)}const vt=new WeakMap;function Pt(e){return vt.get(e)||null}function Tt(e,t){null!==t?vt.set(e,t):vt.delete(e)}const $t=new WeakMap,Ct=Object.freeze([]),Et=new Set;function kt(e,t,n){const s=Array.isArray(t)&&t.length>0?t:Ct,o=Array.isArray(n)&&n.length>0?n:Ct,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Ct,s=Array.isArray(t)&&t.length>0?t:Ct;let o=$t.get(n);return o&&o.get(s)||null}(s,o);if(r)return r;const i=Pt(s)||[];let a;try{if(0===o.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:Et,deleteIndexSet:new Set(i),addIndexSet:Et};let t=Pt(o);if(0===s.length){if(null===t){t=[];for(let n=0;n<o.length;n++){const s=_t(e,n);t.push(s)}}return a={oldIndexes:i,newIndexes:t,changeIndexSet:Et,deleteIndexSet:Et,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}(s,o))return a={oldIndexes:i,newIndexes:i,changeIndexSet:Et,deleteIndexSet:Et,addIndexSet:Et};const n=new Map;for(let e=0;e<s.length;e++){const t=s[e];let o=n.get(t);o||(o=[],n.set(t,o)),o.push(e)}if(null!==t)return function(e,t,n,s,o){const r=new Set(s),i=new Set(n),a=new Set,c=r.difference(i),l=i.difference(r);for(let e=0;e<t.length;e++){const s=t[e],r=o.get(s),i=r&&r.length>0?r.shift():void 0;if(void 0!==i){const t=n[i];t.index!==e&&a.add(t)}}return{oldIndexes:n,newIndexes:s,changeIndexSet:a,deleteIndexSet:l,addIndexSet:c}}(0,o,i,t,n);t=[];const r=new Set,c=new Set;for(let s=0;s<o.length;s++){const a=o[s],l=n.get(a),d=l&&l.length>0?l.shift():void 0;if(void 0===d){const n=_t(e,s);t.push(n),c.add(n)}else{const e=i[d];e.index!==s&&(e.index=s,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 s=$t.get(e);s||(s=new WeakMap,$t.set(e,s)),s.set(t,n)}(s,o,a),Tt(o,a.newIndexes))}}const Mt=new WeakMap;function Ot(e){let t=null;return t=Mt.get(e)||null,null===t&&(t=new Set,Mt.set(e,t)),t}function Dt(e,t){Ot(e).add(t)}function Lt(e,t){Ot(e).delete(t)}const Wt=new WeakMap;function Rt(e){Wt.delete(e)}const Ft=new WeakMap;function Bt(e){return Ft.get(e)??[]}function jt(e,t){Ft.set(e,t)}const qt=new WeakMap;function zt(e){return qt.get(e)??[]}function Ht(e,t){qt.set(e,t)}function Vt(e,t){const n=zt(e);for(const e of n)Ae(e,t)}function Ut(e,t,n){Vt(e,t);const s=Bt(e);for(const e of s){Dt(ut(e),e),$n(e,n)}}function Jt(e){if(!e.mounted)return;const t=Bt(e);for(const e of t){Lt(ut(e),e),ft(e),Rt(e)}!function(e){const t=zt(e);for(const e of t)Ae(e,null)}(e)}const Yt=new WeakMap,Gt=Object.freeze(new Set);function Xt(e,t){const n=Yt.get(e);n?n.add(t):Yt.set(e,new Set([t]))}function Kt(e){const t=Yt.get(e);return void 0!==t?t:Gt}const Qt=new Set(["if","elseif","else","for"]);class Zt{_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(){for(const e of this._childNodeArray)null!==e.parentNode&&e.parentNode.removeChild(e);const e=Bt(this);for(const t of e){if(Qt.has(t.bindingType)){const e=Kt(t.node);for(const t of e)t.unmount()}Rt(t),ft(t)}this._mounted=!1}}function en(e){const t=document.createDocumentFragment(),n=new Zt(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 tn(e){void 0!==e.uuid&&null!==e.uuid||i("BindingInfo.uuid is null.");const t=Ss(e.uuid);t||i(`Fragment with UUID "${e.uuid}" not found.`);const n=document.importNode(t.fragment,!0),s=function(e,t){const[n,s]=function(e,t){const n=[],s=[];for(const o of t){const t=W(e,o.nodePath);if(null===t&&i(`Node not found by path [${o.nodePath.join(", ")}] in fragment.`),de.has(t))continue;const r=ue(t,o.parseBindTextResults,{allowDeferred:!1});s.push(...r.bindings),n.push(t)}return[n,s]}(e,t);return Fn(s),{nodes:n,bindingInfos:s}}(n,t.nodeInfos),o=new Zt(n);jt(o,s.bindingInfos);const r=[];for(const e of s.bindingInfos)e.statePathName in b&&r.push(e);return Nt(o,r),Ht(o,s.nodes),Xt(e.node,o),o}const nn=new WeakMap,sn=new WeakMap,on=new WeakMap,rn=new WeakMap;function an(e,t,n){fn(e,t,n)}function cn(e,t){nn.set(e,t)}function ln(e){return on.get(e.node)||[]}function dn(e,t){const n=on.get(e.node);void 0===n?on.set(e.node,[t]):n.push(t)}function un(e,t){let n=sn.get(e);if(void 0===n)return null;const s=n.get(t);return void 0===s?null:s}function fn(e,t,n){let s=sn.get(e);if(void 0===s){if(null===n)return;s=new WeakMap,sn.set(e,s)}null===n?s.delete(t):s.set(t,n)}const pn=new WeakMap;function hn(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function mn(e,n,o){const r=e.node.isConnected,i=Boolean(o);let a;const c=Kt(e.node);a=0===c.size?tn(e):c.values().next().value;const l=t(),d=e.uuid??"",u=e.bindingType;try{if(i||(s.debug&&console.log(`unmount if content : ${hn(e)}`),Jt(a),a.unmount()),i){if(s.debug&&console.log(`mount if content : ${hn(e)}`),l){const t=document.createComment(`@@wcs-${u}-start:${d}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),a.mountAfter(t);const n=document.createComment(`@@wcs-${u}-end:${d}:${e.statePathName}`),s=a.lastNode??t;s.parentNode.insertBefore(n,s.nextSibling)}else a.mountAfter(e.node);Ut(a,Se(e.node),n)}}finally{pn.set(e.node,r)}}const gn=new WeakMap;function bn(e){return gn.get(e)??[]}const yn=new Set;const wn={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"),s=Number(t);for(let e=0;e<n.length;e++)e===s?n[e].setAttribute("selected",""):n[e].removeAttribute("selected")}};function Nn(e,n,o){if(void 0===o)return void(s.debug&&console.debug("Skipped property write: state value is undefined.",{element:e.node,propSegments:e.propSegments,statePathName:e.statePathName}));const r=e.node,i=e.propSegments;if(1===i.length){const e=i[0];if(r[e]!==o){let t=!1;try{r[e]=o,t=!0}catch(t){s.debug&&console.warn(`Failed to set property '${e}' on element.`,{element:r,newValue:o,error:t})}if(t){const t=function(e,t){const n=M(e);if(null===n)return null;const s=customElements.get(n);if(void 0===s)return null;const o=s.wcBindable;if("wc-bindable"!==o?.protocol||1!==o?.version)return null;const r=o.inputs;if(!Array.isArray(r))return null;for(const e of r)if(e.name===t&&"string"==typeof e.attribute&&e.attribute.length>0)return e.attribute;return null}(r,e);if(null!==t)try{!function(e,t,n){if(null==n)return void e.removeAttribute(t);let s;if("object"==typeof n)try{s=JSON.stringify(n)}catch{s=String(n)}else s=String(n);e.setAttribute(t,s)}(r,t,o)}catch(e){s.debug&&console.warn(`Failed to mirror attribute '${t}' on element.`,{element:r,newValue:o,error:e})}}}if(t()){const t=wn[e];t?t(r,o):(!function(e,t,n){let s=gn.get(e);s||(s=[],gn.set(e,s));const o=s.find(e=>e.propName===t);o?o.value=n:s.push({propName:t,value:n})}(r,e,o),a=r,yn.add(a))}return}var a;let c=r[i[0]];for(let e=1;e<i.length-1;e++){const t=i[e];if(null==c)return;c=c[t]}const l=c[i[i.length-1]];if(l!==o){if(Object.isFrozen(c))return void(s.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:l,newValue:o}));try{c[i[i.length-1]]=o}catch(e){s.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:l,newValue:o,error:e})}}}const xn=new WeakSet;function Sn(e,t,n){const s=e.node,o=e.propSegments;o.length<=1&&i(`Invalid propSegments for web component binding: ${o.join(".")}`);const[r,...a]=o,c=s[r];void 0===c&&i(`Property "${r}" not found on web component.`),c[a.join(".")]=n}function An(e,t){const n=function(e){let t=null;if(t=Wt.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=lt(e);null===n&&i(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=be(e.statePathInfo,n)}else t=be(e.statePathInfo,null);return Wt.set(e,t),t}(t);if(n.pathInfo.path in b){const e=Se(t.node);return null===e&&i(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&i("ListIndex not found for loopContext:");const n=b[t];void 0===n&&i(`Invalid index name: ${t}`);const s=e.listIndex.at(n);return null===s&&i(`Index not found at position ${n} for loopContext:`),s.index}(e,n.pathInfo.path)}return e[ve](n)}const In={class:function(e,t,n){const s=e.node,o=e.propSegments[1];"boolean"!=typeof n&&i("Invalid value for class application: expected boolean, got "+typeof n),s.classList.toggle(o,n)},attr:function(e,t,n){const s=e.node,o=e.propSegments[1];s.getAttribute(o)!==n&&s.setAttribute(o,n)},style:function(e,t,n){const s=e.propSegments[1],o=e.node.style;o[s]!==n&&(o[s]=n)},command:function(e,t,n){Ne(n)||i("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const s=n,o=bt.get(e);if(o&&o.token===s)return;const r=e.node,a=e.propSegments[1];"string"==typeof a&&0!==a.length||i('command binding requires a method name (e.g., "command.fetch").');const c=function(e){const t=M(e);if(null===t)return null;const n=customElements.get(t);void 0===n&&i(`Custom element <${t}> is not defined for command binding.`);const s=n.wcBindable;return"wc-bindable"===s?.protocol&&1===s?.version?s:null}(r);null===c&&i(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),Array.isArray(c.commands)&&c.commands.some(e=>e.name===a)||i(`Command "${a}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.`),o&&(o.unsubscribe(),bt.delete(e));const l=new WeakRef(r);let d=null;d=s.subscribe((...t)=>{const n=l.deref();if(!n||!n.isConnected)return d?.(),void bt.delete(e);const s=n[a];return"function"!=typeof s&&i(`Method "${a}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(s,n,t)}),bt.set(e,{token:s,unsubscribe:d,elementRef:l})}},_n={text:function(e,n,s){if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!xn.has(e.replaceNode)){xn.add(e.replaceNode);const t=e.replaceNode.parentNode;if(t){const n=e.statePathName,s=document.createComment(`@@wcs-text-start:${n}`),o=document.createComment(`@@wcs-text-end:${n}`);t.insertBefore(s,e.replaceNode),t.insertBefore(o,e.replaceNode.nextSibling)}}},for:function(e,n,s){const o=e.statePathInfo,r=lt(e),a=ut(e),c=Ye(a),l=kt(r,c,s);if(n.newListValueByAbsAddress.set(a,Array.isArray(s)?s:[]),Array.isArray(c)&&c.length===l.deleteIndexSet.size&&l.deleteIndexSet.size>0&&null!==e.node.parentNode){let t=rn.get(e.node);if(void 0===t){const n=nn.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,s=t.nextSibling,o=!0;for(;null!==n;){if(n.nodeType===Node.ELEMENT_NODE||n.nodeType===Node.TEXT_NODE&&""!==(n.textContent?.trim()??"")){o=!1;break}n=n.previousSibling}for(;null!==s;){if(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE&&""!==(s.textContent?.trim()??"")){o=!1;break}s=s.nextSibling}return o}(e.node,n),rn.set(e.node,t)}if(t){const t=e.node.parentNode;t.textContent="",t.appendChild(e.node)}}for(const t of l.deleteIndexSet){const n=un(e.node,t);null!==n&&(Jt(n),n.unmount(),dn(e,n),fn(e.node,t,null))}let d=e.node;const u=C(o.path+"."+p),f=n.stateElement.loopContextStack;let h=null;l.newIndexes.length==l.addIndexSet.size&&l.newIndexes.length>0&&d.isConnected&&(h=document.createDocumentFragment(),ot(h,n.rootNode));const m=t(),g=e.uuid??"";for(const t of l.newIndexes){let s;if(l.addIndexSet.has(t)){const r=be(u,t);f.createLoopContext(r,r=>{const i=ln(e);if(s=i.pop(),void 0===s&&(s=tn(e)),null!==h)m&&h.appendChild(document.createComment(`@@wcs-for-start:${g}:${o.path}:${t.index}`)),s.appendTo(h),m&&h.appendChild(document.createComment(`@@wcs-for-end:${g}:${o.path}:${t.index}`));else{if(d.nextSibling!==s.firstNode){if(m){const e=document.createComment(`@@wcs-for-start:${g}:${o.path}:${t.index}`);d.parentNode.insertBefore(e,d.nextSibling),d=e}s.mountAfter(d)}if(m){const e=document.createComment(`@@wcs-for-end:${g}:${o.path}:${t.index}`),n=s.lastNode??d;n.parentNode.insertBefore(e,n.nextSibling)}}Ut(s,r,n)}),void 0===s&&i(`Content not found for ListIndex: ${t.index} at path "${o.path}"`)}else{if(s=un(e.node,t),l.changeIndexSet.has(t)){const e=wt(s);for(const t of e)$n(t,n)}null===s&&i(`Content not found for ListIndex: ${t.index} at path "${o.path}"`),d.nextSibling!==s.firstNode&&s.mountAfter(d)}d=s.lastNode||d,fn(e.node,t,s)}nn.set(e.node,d),null!==h&&(e.node.parentNode.insertBefore(h,e.node.nextSibling),ot(h,null))},if:mn,else:mn,elseif:mn,radio:function(e,t,n){const s=e.node,o=mt(s.value,e.inFilters);s.checked=n===o},checkbox:function(e,t,n){const s=e.node,o=mt(s.value,e.inFilters),r=Array.isArray(n)?n:gt;s.checked=r.includes(o)}},vn=new WeakMap,Pn=new WeakMap;function Tn(e,t){const n=mt(An(t.state,e),e.outFilters);if(!0===Pn.get(e))return void t.deferredSelectBindings.push({binding:e,value:n});let s=vn.get(e);if(void 0===s){if(vn.has(e))return ht(e.replaceNode,t.stateElement)?(s=Sn,vn.set(e,s)):s=Nn,void s(e,t,n);if(s=_n[e.bindingType],void 0===s){const n=e.propSegments[0];if(s=In[n],vn.set(e,s),void 0===s){M(e.replaceNode)?ht(e.replaceNode,t.stateElement)?(s=Sn,vn.set(e,s)):s=Nn:(s=Nn,vn.set(e,s))}}if(s===Nn){if("SELECT"===e.node.tagName){const s=e.propSegments[0];if("value"===s||"selectedIndex"===s)return t.deferredSelectBindings.push({binding:e,value:n}),void Pn.set(e,!0)}}s(e,t,n)}else s(e,t,n)}function $n(e,t){if(t.appliedBindingSet.has(e))return;t.appliedBindingSet.add(e);const n=ut(e);if(t.updatedAbsAddressSetByStateElement.has(t.stateElement)){t.updatedAbsAddressSetByStateElement.get(t.stateElement).add(n)}else t.updatedAbsAddressSetByStateElement.set(t.stateElement,new Set([n]));if("event"===e.bindingType)return;const s=M(e.replaceNode);if(s&&void 0===customElements.get(s))return;let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=rt(o),null===o&&i("Root node for fragment not found for binding.")),e.stateName!==t.stateName||o!==t.rootNode){const n=bs(o,e.stateName);null===n&&i(`State element with name "${e.stateName}" not found for binding.`),n.createState("readonly",s=>{const r={stateName:e.stateName,rootNode:o,stateElement:n,state:s,appliedBindingSet:t.appliedBindingSet,newListValueByAbsAddress:t.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:t.updatedAbsAddressSetByStateElement,deferredSelectBindings:t.deferredSelectBindings};Tn(e,r)})}else Tn(e,t)}function Cn(e){let t=0;const n=new Set,o=new Map,r=new Map,a=[];for(;t<e.length;){let c=e[t];const l=c.stateName;if(!1===c.replaceNode.isConnected){s.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${c.bindingType} ${c.statePathName} on ${c.node.nodeName}`,c),t++;continue}let d=c.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=rt(d),null===d&&i("Root node for fragment not found for binding."));const u=bs(d,l);null===u&&i(`State element with name "${l}" not found for binding.`),u.createState("readonly",s=>{const i={rootNode:d,stateName:l,stateElement:u,state:s,appliedBindingSet:n,newListValueByAbsAddress:o,updatedAbsAddressSetByStateElement:r,deferredSelectBindings:a};for(;;){$n(c,i),t++;const n=e[t];if(!n)break;const s=n.replaceNode.getRootNode();if(n.stateName!==l||s!==i.rootNode)break;c=n}})}for(const{binding:e,value:t}of a)Nn(e,0,t);for(const[e,t]of o.entries())Ge(e,t);for(const[e,t]of r.entries())e.createState("writable",e=>{e[Ce](Array.from(t))})}const En=new Map,kn=new Map;const Mn=(e,t,n)=>s=>{const o=s.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("radio"!==o.type)return void console.warn("[@wcstack/state] event.target is not a radio input element.");if(!1===o.checked)return;let r=o.value;for(const e of n)r=e.filterFn(r);const a=bs(o.getRootNode(),e);null===a&&i(`State element with name "${e}" not found for two-way binding.`);const c=Se(o);a.createState("writable",e=>{e[_e](c,()=>{e[t]=r})})};function On(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf("ro")){const t=function(e){let t="input";for(const n of e.propModifiers)n.startsWith("on")&&(t=n.slice(2));return t}(e),n=function(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.stateName}::${e.statePathName}::${t}::${n}`}(e,t);let s=En.get(n);void 0===s&&(s=Mn(e.stateName,e.statePathName,e.inFilters),En.set(n,s)),e.node.addEventListener(t,s);let o=kn.get(n);return void 0===o?(o=new Set([e]),kn.set(n,o)):o.add(e),!0}return!1}const Dn=new Map,Ln=new Map;const Wn=(e,t,n)=>s=>{const o=s.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("checkbox"!==o.type)return void console.warn("[@wcstack/state] event.target is not a checkbox input element.");const r=o.checked;let a=o.value;for(const e of n)a=e.filterFn(a);const c=bs(o.getRootNode(),e);null===c&&i(`State element with name "${e}" not found for two-way binding.`);const l=Se(o);c.createState("writable",e=>{e[_e](l,()=>{let n=e[t];if(Array.isArray(n))if(r)-1===n.indexOf(a)&&(e[t]=n.concat(a));else{const s=n.indexOf(a);-1!==s&&(e[t]=n.toSpliced(s,1))}else e[t]=r?[a]:[]})})};function Rn(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf("ro")){const t=function(e){let t="input";for(const n of e.propModifiers)n.startsWith("on")&&(t=n.slice(2));return t}(e),n=function(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.stateName}::${e.statePathName}::${t}::${n}`}(e,t);let s=Dn.get(n);void 0===s&&(s=Wn(e.stateName,e.statePathName,e.inFilters),Dn.set(n,s)),e.node.addEventListener(t,s);let o=Ln.get(n);return void 0===o?(o=new Set([e]),Ln.set(n,o)):o.add(e),!0}return!1}function Fn(e){for(const t of e)u(t),Oe(t)||Be(t)||(Ue(t),On(t),Rn(t))}function Bn(e){for(const t of e){Dt(ut(t),t);const e=bs(t.replaceNode.getRootNode(),t.stateName);null===e&&i(`State element with name "${t.stateName}" not found for binding.`),"event"!==t.bindingType&&e.setPathInfo(t.statePathName,t.bindingType)}}function jn(e,t){const[n,s,o]=fe(e);for(const e of n)Ae(e,t);Fn(s),Bn(s),Cn(s),function(e,t){for(const n of e)customElements.whenDefined(n.tagName).then(()=>{if(!n.node.isConnected)return;const e=pe(n);0!==e.length&&(Ae(n.node,t),Fn(e),Bn(e),Cn(e))}).catch(e=>{console.error(`[@wcstack/state] deferred spread failed for <${n.tagName}>.`,e)})}(o,t)}const qn=/\{\{\s*(.+?)\s*\}\}/g,zn=new Set(["SCRIPT","STYLE"]);function Hn(e){if(!s.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&&zn.has(e.parentElement.tagName)||Vn(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 s=n[e];t.content.appendChild(s)}for(const n of e.attributes)t.setAttribute(n.name,n.value);e.replaceWith(t),Hn(t.content)}else Hn(e.content)}function Vn(e){const t=e.data;if(qn.lastIndex=0,!qn.test(t))return;qn.lastIndex=0;const n=document.createDocumentFragment();let s,o=0;for(;null!==(s=qn.exec(t));){s.index>o&&n.appendChild(document.createTextNode(t.slice(o,s.index)));const e=s[1];n.appendChild(document.createComment(`@@: ${e}`)),o=s.index+s[0].length}o<t.length&&n.appendChild(document.createTextNode(t.slice(o))),e.parentNode.replaceChild(n,e)}let Un;function Jn(){if(Un)return Un;const e=[],t=X("not",e)(Y);return Un={filterName:"not",args:e,filterFn:t},Un}const Yn=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Gn(e,t){const n=t+f+p,s=e.indexOf("|"),o=e.indexOf("@");let r,i;if(-1!==s?(r=e.slice(0,s).trim(),i=e.slice(s)):-1!==o?(r=e.slice(0,o).trim(),i=e.slice(o)):(r=e.trim(),i=""),"."===r)r=n;else{if(!r.startsWith("."))return e;r=n+f+r.slice(1)}return i.length>0?r+i:r}function Xn(e,t){const n=Yn.exec(e);if(null===n)return e;const s=n[1],o=n[2],r=n[3];return s+Gn(o,t)+r}function Kn(e,t){const n=e.split(";");let s=!1;const o=n.map(e=>{const n=e.trim();if(0===n.length)return e;const o=n.indexOf(":");if(-1===o)return e;const r=n.slice(0,o).trim(),i=n.slice(o+1).trim(),a=Gn(i,t);return a!==i?(s=!0,`${r}: ${a}`):e});return s?o.join(";"):e}function Qn(e,t){return Kn(e,t)}function Zn(e,t){const n=s.bindAttributeName,o=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;o.nextNode();){const e=o.currentNode;if(e.nodeType===Node.COMMENT_NODE){const n=e;n.data=Xn(n.data,t);continue}const s=e;if(s instanceof HTMLTemplateElement)continue;const r=s.getAttribute(n);if(null!==r){const e=Kn(r,t);e!==r&&s.setAttribute(n,e)}}}function es(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 ts(e){const t=[],n=le(e);for(const e of n){const n=ce(e);t.push({nodePath:es(e),parseBindTextResults:n})}return t}function ns(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 ss=new Map([["for",s.commentForPrefix],["if",s.commentIfPrefix],["elseif",s.commentElseIfPrefix],["else",s.commentElsePrefix]]),os=Jn();function rs(e,t){const n=t.outFilters;return{...t,outFilters:[...n,os],bindingType:e}}function is(e,t,n,s){ns(t),"string"==typeof s&&Zn(t,s),as(e,t,s);return{fragment:t,parseBindTextResult:n,nodeInfos:ts(t)}}function as(e,t,n){const o=s.commentElsePrefix,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode(e){const t=e;if("template"===t.tagName.toLowerCase()){if((t.getAttribute(s.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let a=null;const c=[],l=[];for(;r.nextNode();){const e=r.currentNode;l.push(e)}for(const t of l){let r=t.getAttribute(s.bindAttributeName)||"";"string"==typeof n&&(r=Qn(r,n));let l=se(r)[0];const d=ss.get(l.bindingType);if(void 0===d)continue;const u=l.bindingType,f=t.content,p=St();let h=null;const m="for"===u?l.statePathName:n;if("else"===u){null===a&&i("'else' binding found without preceding 'if' or 'elseif' binding."),l=rs("else",a.parseBindTextResult),h=is(e,f,l,m),xs(p,e,h);const n=c.at(-1),s=document.createComment(`@@${d}:${p}`);void 0!==n?(t.remove(),n.fragment.appendChild(s),n.nodeInfos.push({nodePath:es(s),parseBindTextResults:ce(s)})):t.replaceWith(s)}else if("elseif"===u){null===a&&i("'elseif' binding found without preceding 'if' or 'elseif' binding."),h=is(e,f,l,m),xs(p,e,h);const n=document.createComment(`@@${d}:${p}`),s=St(),r={fragment:document.createDocumentFragment(),parseBindTextResult:rs("else",a.parseBindTextResult),nodeInfos:[]};r.fragment.appendChild(n),r.nodeInfos.push({nodePath:es(n),parseBindTextResults:ce(n)}),xs(s,e,r);const u=c.at(-1);c.push(r);const g=document.createComment(`@@${o}:${s}`);void 0!==u?(t.remove(),u.fragment.appendChild(g),u.nodeInfos.push({nodePath:es(g),parseBindTextResults:ce(g)})):t.replaceWith(g)}else{h=is(e,f,l,m),xs(p,e,h);const n=document.createComment(`@@${d}:${p}`);t.replaceWith(n)}"if"===u?(c.length=0,a=h):"elseif"===u?a=h:"else"===u&&(a=null,c.length=0)}}async function cs(e){const t=e.querySelectorAll(s.tagNames.state),n=[];await customElements.whenDefined(s.tagNames.state);for(const e of t){const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function ls(e){if(e===document)await cs(document),Hn(document),as(document,document),jn(document.body,null);else{const t=e;t.host.hasAttribute(s.bindAttributeName)&&await d(t.host),await cs(t),Hn(t),as(t,t),jn(t,null)}}const ds=new Set(["for","if","elseif","else"]);function us(e){if(0===e.length)return{bindingInfos:[],subscriberNodes:[]};const t=e[0].parentNode,n=e[e.length-1].nextSibling,s=document.createElement("div");for(const t of e)s.appendChild(t);const[o,r]=fe(s);for(const e of r)u(e),Oe(e)||Be(e)||(Ue(e),On(e),Rn(e));if(t)for(;s.firstChild;)t.insertBefore(s.firstChild,n);return{bindingInfos:r,subscriberNodes:o}}function fs(e,t,n){const o={for:s.commentForPrefix,if:s.commentIfPrefix,elseif:s.commentElseIfPrefix,else:s.commentElsePrefix}[t];if(!o)return null;const r=`@@${o}:${n}`,i=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const e=i.currentNode;if(e.data===r)return e}return null}function ps(e,t){const n=e;let o=null;for(const[e,r]of t.templates){let t=se(r.getAttribute(s.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&o?t={...o,outFilters:[...o.outFilters,Jn()],bindingType:"else"}:"elseif"===i&&o&&(t={...t,stateName:o.stateName}),"if"===i||"elseif"===i?o=t:"else"===i&&(o=null);const a=document.importNode(r.content,!0),c="for"===i?t.statePathName:void 0;ns(a),"string"==typeof c&&Zn(a,c),as(n,a,c);xs(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:ts(a)})}}async function hs(e){await cs(e);const t=e.querySelectorAll(s.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="${r}". Falling back to full render.`),Ts.cleanupDom(e),!1}for(const n of t)ps(e,n);const n=function(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),s=[];for(;n.nextNode();)s.push(n.currentNode);for(const e of s){const n=Is.exec(e.data);if(!n)continue;const s=n[1],o=n[2],r=o.split(":");let i,a,c=null;"for"===s?(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-${s}-end:${o}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)l.push(d),d=d.nextSibling;t.push({type:s,uuid:i,path:a,index:c,nodes:l})}return t}(document.body);!function(e,t){const n=new Map;for(const s of t){if(0===s.nodes.length)continue;const t=en(s.nodes),{bindingInfos:o,subscriberNodes:r}=us(s.nodes);for(const e of r)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");jt(t,o),Ht(t,r);const i=[];for(const e of o)e.statePathName in b&&i.push(e);if(Nt(t,i),"for"===s.type&&null!==s.index){const r=fs(e,"for",s.uuid);if(r){const e=_t(null,s.index);an(r,e,t),cn(r,s.nodes[s.nodes.length-1]),Xt(r,t),Vt(t,be(C(s.path+"."+p),e));for(const e of o)Dt(ut(e),e);let i=n.get(s.uuid);i||(i=[],n.set(s.uuid,i)),i.push(e)}}else{const n=fs(e,s.type,s.uuid);if(n){Xt(n,t);for(const e of o)Dt(ut(e),e)}}}for(const[t,s]of n){const n=fs(e,"for",t);if(!n)continue;const o=n.getRootNode(),r=Ss(t);if(!r)continue;const i=r.parseBindTextResult.stateName,a=r.parseBindTextResult.statePathName,c=bs(o,i);c&&c.createState("readonly",e=>{const t=e[a];Array.isArray(t)&&Tt(t,s)})}}(document.body,n),Ts.removeBlockBoundaryComments(document.body);const o=[];for(const e of t)e.parentNode&&(o.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());Ts.restoreTextBindings(document.body);const[a,c]=fe(document.body);for(const e of a)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 l=[],d=[];for(const e of c)if(u(e),!Oe(e)&&!Be(e))if(Ue(e),On(e),Rn(e),ds.has(e.bindingType))d.push(e);else{if(e.statePathName.includes(p))continue;l.push(e)}for(const e of[...l,...d]){Dt(ut(e),e);const t=bs(e.replaceNode.getRootNode(),e.stateName);null===t&&i(`State element with name "${e.stateName}" not found for binding.`),"event"!==e.bindingType&&t.setPathInfo(e.statePathName,e.bindingType)}for(const e of d)if("for"===e.bindingType){const t=ut(e),n=bs(e.replaceNode.getRootNode(),e.stateName);n&&n.createState("readonly",n=>{const s=n[e.statePathName];Array.isArray(s)&&Ge(t,s)})}Cn(l);for(const{el:e,parent:t,next:n}of o)t.insertBefore(e,n);const f=e.querySelectorAll(s.tagNames.ssr);for(const t of f){const n=t.hydrateProps;for(const[t,s]of Object.entries(n)){const n=e.querySelector(`[data-wcs-ssr-id="${t}"]`);if(n)for(const[e,t]of Object.entries(s))n[e]=t}}const h=e.querySelectorAll("[data-wcs-completed]");for(const e of h)e.removeAttribute("data-wcs-completed");return!0}const ms=new WeakMap,gs=new WeakMap;function bs(e,t){let n=ms.get(e);return n&&n.get(t)||null}function ys(e){return gs.get(e)??Promise.resolve()}function ws(e,n,o){let r=ms.get(e);if(null===o){if(!r)return;r.delete(n),0===r.size&&ms.delete(e),s.debug&&console.debug(`State element unregistered: name="${n}"`)}else{if(!r){r=new Map,ms.set(e,r);const n=!t()&&o.hasAttribute?.("enable-ssr");if("HTMLDocument"===e.constructor.name||"Document"===e.constructor.name){const t=new Promise(t=>{queueMicrotask(async()=>{if(n){await hs(e)||await ls(e)}else await ls(e);t()})});gs.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise(t=>{queueMicrotask(async()=>{await ls(e),t()})});gs.set(e,t)}}r.has(n)&&i(`State element with name "${n}" is already registered.`),r.set(n,o),s.debug&&console.debug(`State element registered: name="${n}"`,o)}}const Ns=new Map;function xs(e,t,n){if(null===n)Ns.delete(e);else{Ns.set(e,n);const s=n.parseBindTextResult,o=bs(t,s.stateName);null===o&&i(`State element with name "${s.stateName}" not found for fragment info.`),o.setPathInfo(s.statePathName,s.bindingType);for(const e of n.nodeInfos)for(const n of e.parseBindTextResults){const e=bs(t,n.stateName);null===e&&i(`State element with name "${n.stateName}" not found for fragment info node.`),e.setPathInfo(n.statePathName,n.bindingType)}}}function Ss(e){return Ns.get(e)||null}const As=/^@@wcs-(?:for|if|elseif|else):[^-]/,Is=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,_s=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,vs=/^@@wcs-text-start:(.+)$/;function Ps(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class Ts extends HTMLElement{_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=r.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 n=s.tagNames.ssr,o=e instanceof Element?e:e instanceof Document?e.documentElement:null;if(!o)return null;return o.querySelector(`${n}[name="${t}"]`)}static extractStateData(e){const t=e.__state;if(!t||"object"!=typeof t)return{};const n={};for(const[e,s]of Object.entries(t))e.startsWith("$")||"function"==typeof s||(n[e]=s);return n}static buildContent(e,t){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=Ps(JSON.stringify(t)),e.appendChild(n);const o=Array.from(Ns.keys());for(const t of o){const n=Ss(t);if(!n)continue;const o=document.createElement("template");o.setAttribute("id",t);const r=n.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;o.setAttribute(s.bindAttributeName,i);const a=n.fragment.cloneNode(!0);o.content.appendChild(a),e.appendChild(o)}const r=Array.from(yn);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],s=bn(n);if(0===s.length)continue;const o=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",o);const i={};for(const e of s)i[e.propName]=e.value;t[o]=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=Ps(JSON.stringify(t)),e.appendChild(n)}}yn.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(Is.test(e.data)||_s.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;As.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,s=vs.exec(e.data);s&&n.push({comment:e,path:s[1]})}for(const{comment:e,path:t}of n){const n=document.createComment(`@@: ${t}`);e.parentNode.insertBefore(n,e);let s=e.nextSibling;e.remove();const o=`@@wcs-text-end:${t}`;for(;s;){const e=s.nextSibling;if(s.nodeType===Node.COMMENT_NODE&&s.data===o){s.parentNode.removeChild(s);break}s.parentNode.removeChild(s),s=e}}}static cleanupDom(e){const t=document.body,n=e.querySelectorAll(s.tagNames.ssr),o=new Map;for(const e of n){const t=e.querySelectorAll("template[id]");for(const e of t){const t=e.getAttribute("id");t&&o.set(t,e)}}const r=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const e=r.currentNode;Is.test(e.data)&&i.push(e)}for(const e of i){const t=Is.exec(e.data),n=`@@wcs-${t[1]}-end:${t[2]}`;let s=e.nextSibling;for(;s;){const e=s.nextSibling;if(s.nodeType===Node.COMMENT_NODE&&s.data===n){s.remove();break}s.remove(),s=e}e.remove()}Ts.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),c=[];for(;a.nextNode();){const e=a.currentNode;if(As.test(e.data)){const t=e.data.split(":")[1];c.push({comment:e,uuid:t})}}for(const{comment:e,uuid:t}of c){const n=o.get(t);if(n){const t=document.createElement("template"),o=n.getAttribute(s.bindAttributeName);o&&t.setAttribute(s.bindAttributeName,o);const r=document.importNode(n.content,!0);if(r.childNodes.length>0)t.content.appendChild(r);else for(const e of Array.from(n.childNodes))t.content.appendChild(document.importNode(e,!0));e.parentNode.replaceChild(t,e)}}const l=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of l)e.removeAttribute("data-wcs-ssr-id");for(const e of n)e.remove()}}async function $s(e,t){let n=null;const s=`\n//# sourceURL=${t}\n`;if("function"==typeof URL.createObjectURL){const t=new Blob([e.text+s],{type:"application/javascript"}),o=URL.createObjectURL(t);try{n=await import(o)}finally{URL.revokeObjectURL(o)}}else{const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(e.text+s)));n=await import(`data:application/javascript;base64,${t}`)}return n&&"object"==typeof n.default?n.default:{}}async function Cs(e){try{return(await import(e)).default||{}}catch(e){i(`Failed to load script file: ${e}`)}}class Es{_loopContextStack=Array(h).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&i("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=h&&i("Exceeded maximum loop context stack depth of 128. Possible infinite loop.");const s=this._loopContextStack[this._length-1];if(void 0!==s){s.pathInfo.wildcardCount+1!==n.pathInfo.wildcardCount&&i("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];s.pathInfo!==e&&i("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else 1!==n.pathInfo.wildcardCount&&i("Cannot push loop context for a list with wildcard positions when there is no active loop context.");let o;this._loopContextStack[this._length]=n,this._length++;try{o=t(n)}finally{o instanceof Promise?o.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return o}}const ks=new WeakMap;function Ms(e,t){let n=ks.get(e);void 0===n&&(n=new Map,ks.set(e,n));let s=n.get(t);return void 0===s&&(s=new we(t),n.set(t,s)),s}const Os=new WeakMap;function Ds(e){const t=Os.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 Ms(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:Ms(e,n)}},set(){i("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){i("$command namespace is read-only; deleting from it is not allowed.")}});return Os.set(e,n),n}function Ls(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 Ws(e){return function(t){const n=this.stateElement;n&&n.initializePromise.then(()=>{n.createState("writable",n=>{n[e]=t})})}}function Rs(e,t){return t?function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let s;return n.createStateAsync("writable",async n=>{s=await n[e](...t)}).then(()=>s)})}:function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let s;return n.createState("writable",n=>{s=n[e](...t)}),s})}}function Fs(e){return e.startsWith("$")}const Bs=new Map;class js{path;segments;paths;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(e){const t=e.split("."),n=t.slice(),s=[];let o=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),o++,a++;else{const t=Number(c);Number.isNaN(t)||(n[e]="*",l.push(t),r++,a++)}i+=c,s.push(i),i+=e<c.length-1?".":""}const d=C(n.join("."));(o>0||r>0)&&(c=o===a?"context":r===a?"all":"partial"),this.path=e,this.segments=t,this.paths=s,this.wildcardCount=a,this.wildcardType=c,this.wildcardIndexes=l,this.pathInfo=d}}function qs(e){let t;return Bs.get(e)??(Bs.set(e,t=new js(e)),t)}const zs=new WeakMap;function Hs(e,t){null===t?zs.delete(e):zs.set(e,t)}function Vs(e){const t=zs.get(e);t&&(t.dirty=!0)}function Us(e,t,n,s,o){if(t.pathInfo.segments[0]===I){let e=Ds(o);for(let n=1;n<t.pathInfo.segments.length;n++){if(null==e)return;e=Reflect.get(e,t.pathInfo.segments[n])}return e}if(!(t.pathInfo.path in e)){const o=Ys(e,t.parentAddress??i(`address.parentAddress is undefined path: ${t.pathInfo.path}`),n,s),r=t.pathInfo.segments[t.pathInfo.segments.length-1];if(r===p){const e=t.listIndex?.index??i(`address.listIndex?.index is undefined path: ${t.pathInfo.path}`);return Reflect.get(o,e)}return Reflect.get(o,r)}if(!o.getterPaths.has(t.pathInfo.path))return Reflect.get(e,t.pathInfo.path);s.pushAddress(t);try{return Reflect.get(e,t.pathInfo.path,n)}finally{s.popAddress()}}function Js(e,t,n,s,o){const r=nt(Ke(o,t.pathInfo),t.listIndex),i=function(e){return zs.get(e)??null}(r);if(null!==i&&!1===i.dirty)return i.value;const a=Us(e,t,n,s,o);return Hs(r,{value:a,dirty:!1}),a}function Ys(e,t,n,s){!function(e,t){if(e.addressStackLength>0){const n=e.lastAddressStack?.pathInfo??null,s=e.stateElement;null!==n&&s.getterPaths.has(n.path)&&n.path!==t.pathInfo.path&&s.addDynamicDependency(t.pathInfo.path,n.path)}}(s,t);const o=s.stateElement;return t.pathInfo.wildcardCount>0||o.getterPaths.has(t.pathInfo.path)?Js(e,t,n,s,o):Us(e,t,n,s,o)}function Gs(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const s=n.pathInfo.indexByWildcardPath[t];return void 0===s?null:n.listIndex?.at(s)??null}const Xs=new class{_queueAbsoluteAddresses=[];constructor(){}enqueueAbsoluteAddress(e){const t=0===this._queueAbsoluteAddresses.length;this._queueAbsoluteAddresses.push(e),t&&queueMicrotask(()=>{const e=this._queueAbsoluteAddresses;this._queueAbsoluteAddresses=[],this._applyChange(e)})}testApplyChange(e){this._applyChange(e)}_applyChange(e){const t=new Set(e),n=[];for(const e of t){const t=Ot(e);for(const e of t)!1!==e.replaceNode.isConnected&&n.push(e)}Cn(n)}};function Ks(){return Xs}const Qs=new WeakMap;function Zs(e,t){null===t?Qs.delete(e):Qs.set(e,t)}function eo(e,t,n){const o=C(e.wildcardParentPaths[t]),r=Ke(e.stateElement,o),i=be(o,n),a=Ye(nt(r,n)),c=e.stateProxy[ve](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 s.debug&&console.log(`Invalid search type: ${t}`),[]}}(kt(i.listIndex,a,c),e.searchType);if(t===e.wildcardPaths.length-1)e.targetListIndexes.push(...l);else for(const n of l)eo(e,t+1,n)}function to(e,t,n,s,o,r,a,c,l){const d={stateElement:t,staticMap:s,dynamicMap:o,result:new Set,listPathSet:r,visited:new Set,stateProxy:a,searchType:c};return function(e,t,n){const s=[{address:t,depth:0}];for(;s.length>0;){const{address:t,depth:o}=s.pop();if(o>1e3&&i(`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,a=o+1,c=[],l=e.staticMap.get(r);if(l)for(const n of l){const s=C(n);if(e.listPathSet.has(r)&&s.lastSegment===p){const n=e.stateProxy[ve](t),o=Ye(nt(Ke(e.stateElement,t.pathInfo),t.listIndex)),r=kt(t.listIndex,o,n);for(const t of r.newIndexes){const n=be(s,t);e.result.add(n),c.push({address:n,depth:a})}}else{const n=be(s,t.listIndex);e.result.add(n),c.push({address:n,depth:a})}}const d=e.dynamicMap.get(r);if(d)for(const n of d){const s=C(n),o=[];if(s.wildcardCount>0){const n=at(t.pathInfo,s);if(s.wildcardCount-n>=1){let r;n>0?(null===t.listIndex&&i(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),r=t.listIndex.at(n-1)):r=null;const a={stateElement:e.stateElement,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};eo(a,n,r),o.push(...a.targetListIndexes)}else{null===t.listIndex&&i(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=t.listIndex.at(n-1);o.push(e)}}else o.push(null);for(const t of o){const n=be(s,t);e.result.add(n),c.push({address:n,depth:a})}}for(let e=c.length-1;e>=0;e--)s.push(c[e])}}(d,n,l),Array.from(d.result)}function no(e,t,n,s,o,r){try{if(!(t.pathInfo.path in e)){const n=Ys(e,t.parentAddress??i(`address.parentAddress is undefined path: ${t.pathInfo.path}`),o,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===p){const e=t.listIndex?.index??i(`address.listIndex?.index is undefined path: ${t.pathInfo.path}`);return Reflect.set(n,e,s)}return Reflect.set(n,a,s)}if(!r.stateElement.setterPaths.has(t.pathInfo.path))return Reflect.set(e,t.pathInfo.path,s);r.pushAddress(t);try{return Reflect.set(e,t.pathInfo.path,s,o)}finally{r.popAddress()}}finally{const e=Ks();e.enqueueAbsoluteAddress(n),to(r.stateName,r.stateElement,t,r.stateElement.staticDependency,r.stateElement.dynamicDependency,r.stateElement.listPaths,o,"new",n=>{if(n===t)return;const s=nt(Ke(r.stateElement,n.pathInfo),n.listIndex);Vs(s),e.enqueueAbsoluteAddress(s)})}}function so(e,t,n,s,o,r){let a=t.parentAddress??i(`address.parentAddress is undefined path: ${t.pathInfo.path}`),c=function(e){return Qs.get(e)??null}(a);if(null===c){const t=Ys(e,a,o,r)??[],n=Pt(t)??[];c={value:[...t],listIndexes:[...n]},Zs(a,c)}try{return no(e,t,n,s,o,r)}finally{const n=c.value.indexOf(s),i=Ys(e,a,o,r)??[],l=Array.isArray(i)?Pt(i)??[]:[],d=t.listIndex.index,u=-1!==n?c.listIndexes[n]:_t(a.listIndex,-1);l[d]=u;if(new Set(i).size===c.value.length){for(let e=0;e<l.length;e++)l[e].index=e;Zs(a,null)}}}function oo(e,t,n,o,r){const i=r.stateElement;if(s.sameValueGuard&&(null===n||"object"!=typeof n)){const s=Ys(e,t,o,r);if(Object.is(s,n))return!0}const a=i.elementPaths.has(t.pathInfo.path),c=t.pathInfo.wildcardCount>0||i.getterPaths.has(t.pathInfo.path),l=nt(Ke(i,t.pathInfo),t.listIndex);try{return a?so(e,t,l,n,o,r):no(e,t,l,n,o,r)}finally{c&&Hs(l,{value:n,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:n,bubbles:!0}))}}}function ro(e,t,n,s){return(t,o,r)=>{const a=C(t);if(s.addressStackLength>0){const e=s.lastAddressStack?.pathInfo??null,t=s.stateElement;null!==e&&e.path!==a.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(a.path,e.path)}a.wildcardParentPathInfos.length>o.length&&i(`indexes length is insufficient: ${t}`);let c=null;for(let t=0;t<a.wildcardParentPathInfos.length;t++){const r=a.wildcardParentPathInfos[t],l=be(r,c),d=Pt(Ys(e,l,n,s));null==d&&i(`ListIndexes not found: ${r.path}`);c=d[o[t]]??i(`ListIndex not found: ${r.path}`)}const l=be(a,c);if(!(void 0!==r))return Ys(e,l,n,s);oo(e,l,r,n,s)}}const io=new WeakMap;function ao(e,t,n,s){const o=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return Gs(s,o.wildcardPaths.at(-1)??i(`lastWildcardPath is null: ${t.pathInfo.path}`))??i(`ListIndex not found: ${t.pathInfo.path}`);case"all":{let o=null;for(let r=0;r<t.pathInfo.wildcardCount;r++){const a=t.pathInfo.wildcardParentPathInfos[r]??i(`wildcardParentPathInfo is null: ${t.pathInfo.path}`);o=(Pt(Ys(e,be(a,o),n,s))??i(`ListIndex not found: ${a.path}`))[t.wildcardIndexes[r]??i(`wildcardIndex is null: ${t.pathInfo.path}`)]??i(`ListIndex not found: ${a.path}`)}return o}case"partial":i(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function co(e,t,n){void 0!==e.loopContext&&i("already in loop context"),e.setLoopContext(t);try{e.pushAddress(t);try{return n()}finally{e.popAddress()}}finally{e.clearLoopContext()}}function lo(e,t,n,s){const o=b[t];if(void 0!==o){0===s.addressStackLength&&i(`No active state reference to get list index for "${t.toString()}".`);const e=s.lastAddressStack?.listIndex;return e?.indexes[o]??i(`ListIndex not found: ${t.toString()}`)}if("string"==typeof t){if("$"!==t[0]){const o=qs(t),r=ao(e,o,n,s),i=be(o.pathInfo,r);return Ys(e,i,n,s)}switch(t){case"$stateElement":return s.stateElement;case"$getAll":return(t,o)=>function(e,t,n,s){const o=ro(e,0,n,s);return(t,r)=>{const a=new Map,c=C(t);if(s.addressStackLength>0){const e=s.lastAddressStack?.pathInfo??null,t=s.stateElement;null!==e&&e.path!==c.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(c.path,e.path)}if(void 0===r){for(let e=0;e<c.wildcardParentPathInfos.length;e++){const t=c.wildcardParentPathInfos[e],n=Gs(s,t.path);if(n){r=n.indexes;break}}void 0===r&&(r=[])}const l=(t,o,r,c,d,u,f)=>{const p=t[o]??null;if(null===p)return void f.push(u);const h=be(p,r),m=io.get(h),g=Ys(e,h,n,s),b=kt(r,m,g).newIndexes,y=c[d]??null;if(a.set(h,g),null===y)for(let e=0;e<b.length;e++){const n=b[e];l(t,o+1,n,c,d+1,u.concat(n.index),f)}else{const e=b[y]??i(`ListIndex not found: ${p.path}`);o+1<t.length?l(t,o+1,e,c,d+1,u.concat(e.index),f):f.push(u.concat(e.index))}},d=[];l(c.wildcardParentPathInfos,0,null,r,0,[],d);const u=[];for(let e=0;e<d.length;e++)u.push(o(c.path,d[e]));for(const[e,t]of a.entries())io.set(e,t);return u}}(e,0,n,s)(t,o);case"$postUpdate":return t=>function(e,t,n,s){const o=s.stateElement;return t=>{const r=qs(t),i=ao(e,r,n,s),a=be(r.pathInfo,i),c=nt(Ke(o,a.pathInfo),a.listIndex),l=Ks();l.enqueueAbsoluteAddress(c),to(s.stateName,s.stateElement,a,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",e=>{const t=nt(Ke(o,e.pathInfo),e.listIndex);Vs(t),l.enqueueAbsoluteAddress(t)})}}(e,0,n,s)(t);case"$resolve":return(t,o,r)=>ro(e,0,n,s)(t,o,r);case"$trackDependency":return e=>function(e,t,n,s){return e=>{0===s.addressStackLength&&i(`No active state reference to track dependency for path "${e}".`);const t=s.lastAddressStack?.pathInfo??i("Internal error: lastAddressStack is null"),n=s.stateElement;s.stateElement.getterPaths.has(t.path)&&t.path!==e&&n.addDynamicDependency(e,t.path)}}(0,0,0,s)(e);case I:return Ds(s.stateElement)}}else if("symbol"==typeof t){switch(t){case Ie:return(e,t=async()=>{})=>async function(e,t,n){return await co(e,t,n)}(s,e,t);case _e:return(e,t=()=>{})=>function(e,t,n){return co(e,t,n)}(s,e,t);case ve:return t=>Ys(e,t,n,s);case Pe:return(t,o)=>oo(e,t,o,n,s);case Te:return()=>async function(e,t,n){const s=Reflect.get(e,y);"function"==typeof s&&await s.call(n)}(e,0,n);case $e:return()=>function(e,t,n){const s=Reflect.get(e,w);"function"==typeof s&&s.call(n)}(e,0,n);case Ce:return t=>function(e,t,n,s){const o=Reflect.get(e,N);if("function"==typeof o){const e=new Set,r={};for(const n of t){const t=n.absolutePathInfo.pathInfo;let o;if(o=n.absolutePathInfo.stateName===s.stateName?t.path:t.path+"@"+n.absolutePathInfo.stateName,e.add(o),t.wildcardCount>0){const e=n.listIndex.indexes??[],t=r[o];void 0===t?r[o]=[e]:t.push(e)}}return o.call(n,Array.from(e),r)}}(e,t,n,s)}return Reflect.get(e,t,n)}}class uo{_stateElement;_stateName;_addressStack=Array(h).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;constructor(e,t,n){this._stateName=t;const s=bs(e,this._stateName);null===s&&i(`StateHandler: State element with name "${this._stateName}" not found.`),this._stateElement=s,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&&i("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex++,this._addressStackIndex>=h&&i("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&&i(`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 lo(e,t,n,this)}set(e,t,n,s){return"readonly"===this._mutability&&i(`State "${this._stateName}" is readonly.`),function(e,t,n,s,o){if("string"==typeof t){const r=qs(t),i=ao(e,r,s,o);return oo(e,be(r.pathInfo,i),n,s,o)}return Reflect.set(e,t,n,s)}(e,t,n,s,this)}has(e,t){return Reflect.has(e,t)}}const fo=new WeakMap;const po=new WeakMap;function ho(e,t){const n=po.get(e);return n?n.get(t)??null:null}const mo=new WeakMap,go=new WeakMap,bo=new WeakMap,yo=new WeakMap;function wo(e,t){return{innerAbsPathInfo:Ke(e,C(t.propSegments.slice(1).join(f))),outerAbsPathInfo:ut(t).absolutePathInfo}}function No(e,t){let n=mo.get(e);if(void 0===n&&(n=new Map,mo.set(e,n)),n.has(t))return n.get(t);let s=go.get(e);void 0===s&&(s=new Map,go.set(e,s));const o=bo.get(e);if(void 0===o)return null;let r=null;for(const e of o)if(t.pathInfo.cumulativePathInfoSet.has(e.innerAbsPathInfo.pathInfo)){e.innerAbsPathInfo.pathInfo.segments.length===t.pathInfo.segments.length&&i("Duplicate mapping rule for web component."),r=e;break}if(null===r)return null;const a=yo.get(r);void 0===a&&i("Binding not found for primary mapping rule on web component.");const c=t.pathInfo.segments.slice(r.innerAbsPathInfo.pathInfo.segments.length),l=C(r.outerAbsPathInfo.pathInfo.segments.concat(c).join(f)),d=bs(e.getRootNode(),a.stateName);null===d&&i(`State element with name "${a.stateName}" not found for web component.`);const u=Ke(d,l);n.set(t,u),s.set(u,t);return function(e,t){const n=F(e);null===n?B(e,[t]):n.push(t)}(e,{...a,propName:t.pathInfo.path,propSegments:t.pathInfo.segments,statePathName:u.pathInfo.path,statePathInfo:u.pathInfo}),u}function xo(e){return function(e){const t=Object.getPrototypeOf(e),n=Object.create(t),s=Object.getOwnPropertyDescriptors(e);for(const e in s){const t=s[e];!1===t.writable&&(t.writable=!0)}return Object.defineProperties(n,s),n}(e)}class So{_webComponent;_innerStateElement;constructor(e,t){this._webComponent=e,this._innerStateElement=ho(e,t)??i("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 s=C(t),o=Ke(this._innerStateElement,s),r=No(this._webComponent,o);if(null!==r){const e=Se(this._webComponent);let t;return r.stateElement.createState("readonly",n=>{n[_e](e,()=>{t=n[r.pathInfo.path];let s=null;null!==e&&null!==e.listIndex&&r.pathInfo.wildcardCount>0&&(s=e.listIndex.at(r.pathInfo.wildcardCount-1));!function(e,t){fo.set(e,t)}(nt(r,s),t)})}),t}if(t in e)return Reflect.get(e,t,n);i(`Property "${t}" not found in inner state: no mapping rule and no local state property.`)}}set(e,t,n,s){if("string"!=typeof t)return Reflect.set(e,t,n,s);{if(this._innerStateElement.setterPaths.has(t)&&t in e)return Reflect.set(e,t,n,s);const o=C(t),r=Ke(this._innerStateElement,o),a=No(this._webComponent,r);if(null!==a){const e=Se(this._webComponent);return a.stateElement.createState("writable",t=>{t[_e](e,()=>{t[a.pathInfo.path]=n})}),!0}if(t in e)return Reflect.set(e,t,n,s);i(`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=C(t),s=Ke(this._innerStateElement,n);return null!==No(this._webComponent,s)||t in e}return Reflect.has(e,t)}}class Ao{_innerStateElement;constructor(e,t){this._innerStateElement=ho(e,t)??i("State element not found for web component.")}get(e,t,n){if("string"==typeof t){const e=C(t),n=nt(Ke(this._innerStateElement,e),null);return s=n,fo.get(s)}return Reflect.get(e,t,n);var s}set(e,t,n,s){if("string"==typeof t){const e=C(t),n=Ke(this._innerStateElement,e);return this._innerStateElement.createState("readonly",e=>{e.$postUpdate(n.pathInfo.path)}),!0}return Reflect.set(e,t,n,s)}}class Io{_innerStateElement;constructor(e,t){this._innerStateElement=ho(e,t)??i("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,s){return"string"==typeof t?(this._innerStateElement.createState("writable",e=>{e[t]=n}),!0):Reflect.set(e,t,n,s)}}const _o=e=>()=>e;function vo(e,t,n,o){if(function(e,t,n){let s=po.get(e);s||(s=new Map,po.set(e,s)),s.set(t,n)}(t,n,e),t.hasAttribute(s.bindAttributeName)){const s=(F(t)??[]).filter(e=>e.propSegments[0]===n);!function(e,t,n){if(0===n.length)return;const s=ho(e,t);null===s&&i("State element not found for web component.");const o=new Map,r=new Map;for(const t of n){const n=wo(s,t);let i=bo.get(e);void 0===i?bo.set(e,new Set([n])):i.add(n);const a=n.innerAbsPathInfo,c=n.outerAbsPathInfo;yo.set(n,t),o.set(a,c),r.set(c,a)}mo.set(e,o),go.set(e,r)}(t,n,s);const o=function(e,t){const n=new Ao(e,t);return new Proxy({},n)}(t,n),r=function(e,t){const n=new So(e,t),s=ho(e,t);null===s&&i("State element not found for web component."),null===s.boundComponentStateProp&&i("State element is not bound to any component state prop."),s.boundComponentStateProp in e||i(`State element is not bound to a valid component state prop: ${s.boundComponentStateProp}`);const o=e[s.boundComponentStateProp];return"object"==typeof o&&null!==o||i(`Invalid state object for component state prop: ${s.boundComponentStateProp}`),new Proxy(xo(o),n)}(t,n);e.setInitialState(r),Object.defineProperty(t,n,{get:_o(o),enumerable:!0,configurable:!0})}else{e.setInitialState(xo(o));const s=function(e,t){const n=new Io(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:_o(s),enumerable:!0,configurable:!0})}if(function(e,t){let n=pt.get(e);n||(n=new WeakMap,pt.set(e,n)),n.set(t,!0)}(t,e),x in t){const e=t[x];"function"==typeof e?e.call(t,n).catch(e=>{i(`Error in ${x}: ${e instanceof Error?e.message:String(e)}`)}):i(`${x} is not a function.`)}}function Po(e){const t=new Set,n=new Set,s=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,o]of Object.entries(s))"function"==typeof o.get&&t.add(e),"function"==typeof o.set&&n.add(e);return{getterPaths:t,setterPaths:n}}class To extends HTMLElement{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return ys(e)}__state;_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 Es}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;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&&i(`${s.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){this._commandTokenNames=function(e){const t=new Set,n=e[A];if(void 0===n)return t;Array.isArray(n)||i(`${A} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||i(`${A} entries must be non-empty strings.`),e===I&&i(`${A} entry "${e}" conflicts with the reserved namespace name "${I}".`),t.has(e)&&i(`${A} entry "${e}" is duplicated.`),t.add(e);return t}(e),this._eventTokenNames=function(e){const t=new Set,n=e[_];if(void 0===n)return t;Array.isArray(n)||i(`${_} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||i(`${_} entries must be non-empty strings.`),t.has(e)&&i(`${_} entry "${e}" is duplicated.`),t.add(e);return t}(e),this.__state=e,Re(this),function(e,t,n){const s=t[v];if(void 0!==s){"object"==typeof s&&null!==s||i(`${v} must be an object mapping event-token names to handler functions.`);for(const[t,o]of Object.entries(s))n.has(t)||i(`${v} entry "${t}" is not declared in $eventTokens.`),"function"!=typeof o&&i(`${v} entry "${t}" must be a function.`),We(e,t).subscribe(o)}}(this,e,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._pathSet.clear();const t=Po(e);for(const e of t.getterPaths)this._getterPaths.add(e);for(const e of t.setterPaths)this._setterPaths.add(e);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=Ts.findByName(t,e);if(!n)return null;const s=n.stateData;return Object.keys(s).length>0?s:null}async _initialize(){const e=t()?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){i("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||i(`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 Cs(e):i(`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 $s(e,`${this._name}`);else{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${s.tagNames.state}> element with name="${this._name}".`)},6e4);this._state=await this._setStatePromise,clearTimeout(e)}}}catch(e){i(`Failed to initialize state: ${e}`)}if(null!==e&&this.__state)for(const[t,n]of Object.entries(e)){if(t in this.__state){const e=Object.getOwnPropertyDescriptor(this.__state,t);if(e&&(e.get||e.set))continue;if("function"==typeof this.__state[t])continue}this.__state[t]=n}await this._loadingPromise,this._name=this.getAttribute("name")||"default",ws(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,n=t?M(t):null;null!==t&&null!==n||i(`"bind-component" requires <${s.tagNames.state}> to be a direct child of a custom element.`),e instanceof ShadowRoot||this.hasAttribute("name")||i('"bind-component" in Light DOM requires a "name" attribute to avoid namespace conflicts with the parent scope.');const o=this.getAttribute("bind-component");await customElements.whenDefined(n.toLowerCase()),t.hasAttribute(s.bindAttributeName)&&await d(t),o in t||i(`Component does not have property "${o}" for state binding.`);const r=t[o];"object"==typeof r&&null!==r||i(`Component property "${o}" is not an object for state binding.`),this._boundComponent=t,this._boundComponentStateProp=o,vo(this,this._boundComponent,this._boundComponentStateProp,r)}}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{y in e&&await e[Te]()})}async _initializeDCC(e,t){let n;try{if(this.hasAttribute("src")){const e=this.getAttribute("src");e.endsWith(".js")?n=await Cs(e):i(`DCC: Unsupported src type: ${e}`)}else{const t=this.querySelector('script[type="module"]');t?n=await $s(t,e.tagName.toLowerCase()):i(`DCC: No state source found for "${e.tagName.toLowerCase()}".`)}}catch(e){i(`DCC: Failed to load state: ${e}`)}!function(e,t,n){const o=e.tagName.toLowerCase();if(o.includes("-")||i(`DCC: "${o}" is not a valid custom element name (must contain a hyphen).`),customElements.get(o))return void console.warn(`[@wcstack/state] DCC: "${o}" is already registered. Skipping redefinition.`);const r=document.createElement("template");r.innerHTML=t.innerHTML;const a=t.mode,c=Array.isArray(n[S])?n[S]:[],l=c.length>0?function(e,t){return{protocol:"wc-bindable",version:1,properties:t.map(t=>({name:t,event:`${e}:${t}-changed`}))}}(o,c):null,d=c.length>0?function(e,t){const n={};for(const s of t)n[s]=`${e}:${s}-changed`;return n}(o,c):{},u=`${s.tagNames.state}:not([name])`,f=class extends HTMLElement{static template=r;static shadowRootMode=a;static wcBindable=l;static bindableEventMap=d;_shadow=null;connectedCallback(){if(!this.hasAttribute(P)&&(this._shadow=this.attachShadow({mode:f.shadowRootMode}),this._shadow.appendChild(f.template.content.cloneNode(!0)),Object.keys(f.bindableEventMap).length>0)){const e=this._shadow.querySelector(u);e&&e.initializePromise.then(()=>{e.setBindableEventMap(f.bindableEventMap)})}}get stateElement(){return this._shadow?.querySelector(u)}},p=Object.getOwnPropertyDescriptors(n);for(const[e,t]of Object.entries(p)){if(Fs(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const s="AsyncFunction"===t.value.constructor?.name;n.value=Rs(e,s)}else n.get=Ls(e),n.set=Ws(e);Object.defineProperty(f.prototype,e,n)}customElements.define(o,f)}(e,t,n),this._initialized=!0,this._rootNode=null,this._resolveInitialize?.(),this._resolveConnectedCallback?.()}_callStateDisconnectedCallback(){this.createState("writable",e=>{w in e&&e[$e]()})}async connectedCallback(){if(this._rootNode=this.getRootNode(),!this._initialized){const e=this.parentNode;if(e instanceof ShadowRoot&&e.host.hasAttribute(P))return void await this._initializeDCC(e.host,e);await this._initializeBindWebComponent(),await this._initialize(),this._initialized=!0,this._resolveInitialize?.()}if(this.hasAttribute("enable-ssr")&&!t()||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr")){await ys(this.rootNode);const e=this.getAttribute("name")||"default",t=Ts.extractStateData(this),n=document.createElement(s.tagNames.ssr);n.setAttribute("name",e),n.setAttribute("version",r),Ts.buildContent(n,t),this.parentNode?.insertBefore(n,this)}this._resolveConnectedCallback?.()}disconnectedCallback(){var e;null!==this._rootNode&&(this._callStateDisconnectedCallback(),ws(this.rootNode,this._name,null),e=this,ks.delete(e),function(e){Os.delete(e)}(this),Re(this),this._rootNode=null)}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&&i("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 s=e.get(t);return void 0===s?(e.set(t,[n]),!0):!s.includes(n)&&(s.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+"."+p)),!this._pathSet.has(e)){const t=C(e);if(this._pathSet.add(e),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=C(e.parentPath)}}}_createState(e,t,n){try{const s=function(e,t,n,s){const o=new uo(e,n,s);return new Proxy(t,o)}(e,this._state,this._name,t);return n(s)}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}bindProperty(e,t){Object.defineProperty(this._state,e,t)}setInitialState(e){this._initialized?this._state=e:this._resolveSetState?.(e)}}function $o(){customElements.get(s.tagNames.ssr)||customElements.define(s.tagNames.ssr,Ts),customElements.get(s.tagNames.state)||customElements.define(s.tagNames.state,To)}function Co(e){var t;e&&((t=e).tagNames&&Object.assign(n.tagNames,t.tagNames),"string"==typeof t.bindAttributeName&&(n.bindAttributeName=t.bindAttributeName),"string"==typeof t.commentTextPrefix&&(n.commentTextPrefix=t.commentTextPrefix),"string"==typeof t.commentForPrefix&&(n.commentForPrefix=t.commentForPrefix),"string"==typeof t.commentIfPrefix&&(n.commentIfPrefix=t.commentIfPrefix),"string"==typeof t.commentElseIfPrefix&&(n.commentElseIfPrefix=t.commentElseIfPrefix),"string"==typeof t.commentElsePrefix&&(n.commentElsePrefix=t.commentElsePrefix),"string"==typeof t.locale&&(n.locale=t.locale),"boolean"==typeof t.debug&&(n.debug=t.debug),"boolean"==typeof t.enableMustache&&(n.enableMustache=t.enableMustache),"boolean"==typeof t.sameValueGuard&&(n.sameValueGuard=t.sameValueGuard)),$o()}function Eo(e){return e}const ko={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}},Mo=1;function Oo(){return{version:1,syntax:{bindAttribute:s.bindAttributeName,tagName:s.tagNames.state,pathDelimiter:f,wildcard:p,delimiters:{binding:";",propValue:":",modifier:"#",stateName:"@",filter:m},structuralDirectives:Array.from(j)},filters:Object.keys(Y),filterMeta:ko,reservedLifecycle:[y,w,N,x],reservedStateApi:[S,A,I,_,v]}}export{Ts as Ssr,r as VERSION,Mo as WCS_MANIFEST_VERSION,Co as bootstrapState,ls as buildBindings,ko as builtinFilterMeta,Eo as defineState,ys as getBindingsReady,o as getConfig,Oo as getWcsManifest};
2
2
  //# sourceMappingURL=index.esm.min.js.map