@wcstack/state 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.ja.md +128 -90
  2. package/README.md +129 -91
  3. package/dist/auto.min.js +1 -1
  4. package/dist/auto.min.js.map +1 -1
  5. package/dist/define.d.ts +11 -7
  6. package/dist/index.d.ts +58 -15
  7. package/dist/index.esm.js +1 -1
  8. package/dist/index.esm.js.map +1 -1
  9. package/dist/manifest.d.ts +39 -5
  10. package/dist/manifest.esm.js +315 -253
  11. package/dist/parser.d.ts +16 -2
  12. package/dist/parser.esm.js +223 -50
  13. package/dist/split/chunks/binder.js +1 -1
  14. package/dist/split/chunks/binder.js.map +1 -1
  15. package/dist/split/chunks/checkDependency.js +1 -1
  16. package/dist/split/chunks/declarationAliases.js +2 -0
  17. package/dist/split/chunks/declarationAliases.js.map +1 -0
  18. package/dist/split/chunks/declarationHooks.js +2 -0
  19. package/dist/split/chunks/declarationHooks.js.map +1 -0
  20. package/dist/split/chunks/featureBridge.js +2 -0
  21. package/dist/split/chunks/featureBridge.js.map +1 -0
  22. package/dist/split/chunks/filterRegistry.js +1 -1
  23. package/dist/split/chunks/filterRegistry.js.map +1 -1
  24. package/dist/split/chunks/getAllPropertyDescriptors.js +1 -1
  25. package/dist/split/chunks/getAllPropertyDescriptors.js.map +1 -1
  26. package/dist/split/chunks/lifecycleHooks.js +1 -1
  27. package/dist/split/chunks/pathDiagnostics.js +1 -1
  28. package/dist/split/chunks/pathDiagnostics.js.map +1 -1
  29. package/dist/split/chunks/registerComponents.js +1 -1
  30. package/dist/split/chunks/registerComponents.js.map +1 -1
  31. package/dist/split/chunks/setAll.js +1 -1
  32. package/dist/split/chunks/setAll.js.map +1 -1
  33. package/dist/split/chunks/version.js +1 -1
  34. package/dist/split/core.d.ts +21 -9
  35. package/dist/split/core.js +1 -1
  36. package/dist/split/core.js.map +1 -1
  37. package/dist/split/features/devtools.js +1 -1
  38. package/dist/split/features/devtools.js.map +1 -1
  39. package/dist/split/features/diagnostics.js +1 -1
  40. package/dist/split/features/diagnostics.js.map +1 -1
  41. package/dist/split/features/formats.js +1 -1
  42. package/dist/split/features/formats.js.map +1 -1
  43. package/dist/split/features/recursion.js +1 -1
  44. package/dist/split/features/recursion.js.map +1 -1
  45. package/dist/split/features/scopes.js +1 -1
  46. package/dist/split/features/scopes.js.map +1 -1
  47. package/dist/split/features/ssr.js +1 -1
  48. package/dist/split/features/ssr.js.map +1 -1
  49. package/dist/split/features/temporal.js +1 -1
  50. package/dist/split/features/temporal.js.map +1 -1
  51. package/dist/wcs-manifest.json +98 -44
  52. package/package.json +1 -1
  53. package/dist/split/chunks/mount.js +0 -2
  54. package/dist/split/chunks/mount.js.map +0 -1
  55. package/dist/split/chunks/watchRuntime.js +0 -2
  56. package/dist/split/chunks/watchRuntime.js.map +0 -1
package/dist/auto.min.js CHANGED
@@ -1,2 +1,2 @@
1
- const e=Symbol.for("wcstack.ssr.snapshotBuilder");function t(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const n={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,enableDirectionalInitialSync:!0,enablePropagationContext:!0,enableContractAnalyzer:!1,sameValueGuard:!0},o=n;const s=Symbol.for("wcstack.binder");const r=Symbol.for("wcstack.binder.pending"),i=Symbol.for("wcstack.binder.taken");function a(){const e=function(){const e=globalThis[s];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}();if(null===e)return;const t=function(){const e=globalThis;let t=e[r];return void 0===t&&(t=[],e[r]=t),t}();if(0===t.length)return;const n=t.splice(0,t.length),o=function(){const e=globalThis;let t=e[i];return void 0===t&&(t=new WeakSet,e[i]=t),t}();for(const t of n)o.add(t),e.bind(t)}const l=".",c="*",d=128,u=128,f="#",h="|",p="prevent",m="stop",g="ro",y="init",w="sync",b="else",v="...",$="on",x="eventToken",S="state",P="command",I="class",N="attr",k="style",_={};for(let e=0;e<d;e++)_[`$${e+1}`]=e;const A=Object.freeze(_),C="$connectedCallback",E="$disconnectedCallback",M="$updatedCallback",O="$errorCallback",T="$stateReadyCallback",R="$bindables",j="$commands",L="$commandTokens",W="$command",D="$eventTokens",B="$on",z="$streams",F="$watch",q="$scan",V="$recursion",H="**",U="$listKeys",G="$streamStatus",K="$streamError",J="data-wc-definition",X=/\{\{\s*(.+?)\s*\}\}/g,Q=new Set(["SCRIPT","STYLE"]);function Y(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&&Q.has(e.parentElement.tagName)||Z(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),Y(t.content)}else Y(e.content)}function Z(e){const t=e.data;if(X.lastIndex=0,!X.test(t))return;X.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=X.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)}function ee(e){throw new Error(`[@wcstack/state] ${e}`)}const te=new Map;let ne=0;function oe(e){let t=te.get(e);return void 0!==t||(-1!==e.indexOf(H)&&ee(`[wcs/recursion-unsupported] "${e}" uses "${H}", which is not accepted here. It is only meaningful in a $recursion declaration, in a recursive getter key, and in the path argument of $getAll / $setAll — and only when the state declares a $recursion anchor.`),t=Object.freeze(new se(e)),te.set(e,t)),t}class se{id=++ne;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:oe(t),n=e.split("."),o=[],s=[],r=[],i={},a=[],l=[],d=[],u=[];let f="",h="",p=0;for(let e=0;e<n.length;e++)f+=n[e],n[e]===c&&(r.push(f),i[f]=p,a.push(t(f)),l.push(h),d.push(t(h)),u.push(e),p++),o.push(f),s.push(t(f)),h=f,f+=".";const m=r.length>0?r[r.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=e,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=r,this.wildcardPathSet=new Set(r),this.indexByWildcardPath=i,this.wildcardPathInfos=a,this.wildcardPathInfoSet=new Set(a),this.wildcardParentPaths=l,this.wildcardParentPathSet=new Set(l),this.wildcardParentPathInfos=d,this.wildcardParentPathInfoSet=new Set(d),this.wildcardPositions=u,this.lastWildcardPath=m,this.lastWildcardInfo=m?t(m):null,this.parentPath=g,this.parentPathInfo=g?t(g):null,this.wildcardCount=p}}function re(e,t,n){if(Math.abs(e.length-t.length)>n)return n+1;const o=new Array(t.length+1),s=new Array(t.length+1);for(let e=0;e<=t.length;e++)o[e]=e;for(let n=1;n<=e.length;n++){s[0]=n;for(let r=1;r<=t.length;r++){const i=e[n-1]===t[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let e=0;e<=t.length;e++)o[e]=s[e]}return o[t.length]}function ie(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=re(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const ae=" Validate statically: npx @wcstack/lint <file>.",le=new Set(["if","elseif","else","for"]),ce={not:()=>e=>!e},de={input:new Map,output:new Map},ue={input:new Map,output:new Map},fe=new Map;function he(e,t,n){const o=de[e],s=ue[e];for(const e of Object.keys(t)){o.set(e,t[e]);const r=n?.[e];void 0===r?s.delete(e):s.set(e,r)}fe.clear()}function pe(e,t,n,o=t){const s=`${e}${JSON.stringify(o)}:${n}`,r=fe.get(s);if(void 0!==r)return r;const i=de[n].get(e)??ce[e];void 0===i&&ee(`[wcs/filter-unknown] filter not found: ${e}.${ie(e,function(e){return[...new Set([...Object.keys(ce),...de[e].keys()])]}(n))}${ae}`);const a=ue[n].get(e);void 0!==a&&(t.length<a[0]||t.length>a[1])&&ee(t.length<a[0]?`[wcs/filter-arity] filter "${e}" requires at least ${a[0]} argument(s) (${t.length} given).${ae}`:`[wcs/filter-arity] filter "${e}" accepts at most ${a[1]} argument(s) (${t.length} given).${ae}`);const l=i(t,o);return fe.set(s,l),l}function me(e,t,n){const o=-1===t?e.length:t;let s=0;for(;s<o&&/\s/.test(e[s]);)s++;const r=-1===n?0:n;let i=e.length;for(;i>r&&/\s/.test(e[i-1]);)i--;return e.slice(s,i)}const ge=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function ye(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:ge.test(e)?Number(e):e)}function we(e){const t=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const e=me(o,i,a);t.push(e),n.push(ye(e,r)),o="",r=!1,i=-1,a=-1};for(let t=0;t<e.length;t++){const n=e[t];s?n===s?s=null:(-1===i&&(i=o.length),o+=n,a=o.length):'"'===n||"'"===n?(s=n,r=!0):","===n?l():o+=n}null!==s&&ee(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${e})". Close the quote.${ae}`);const c=me(o,i,a);return(c||r)&&(t.push(c),n.push(ye(c,r))),{args:t,literals:n}}function be(e,t){return e.map(t=>{const n=t.indexOf("("),o=t.lastIndexOf(")");-1!==n&&-1===o&&ee(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==o&&-1===n&&ee(`Invalid filter format: missing opening parenthesis in "${t}"`);const s=(-1===n?t:t.substring(0,n)).trim();if(0===s.length&&ee(`[wcs/binding-syntax] an empty filter in "${e.join("|")}" — remove the extra "|" or name the filter.${ae}`),-1===n)return{filterName:s,args:[],literals:[]};return{filterName:s,...we(t.substring(n+1,o))}})}const ve=e=>e.trim(),$e=e=>"'"===e||'"'===e;function xe(e,t){let n=null;for(let o=0;o<e.length;o++){const s=e[o];if(null!==n)s===n&&(n=null);else if($e(s))n=s;else if(s===t)return o}return-1}function Se(e,t){const n=[];let o=null,s=0;for(let r=0;r<e.length;r++){const i=e[r];null!==o?i===o&&(o=null):$e(i)?o=i:i===t&&(n.push(e.slice(s,r)),s=r+1)}return n.push(e.slice(s)),n}const Pe=new Map;function Ie(e){const t=xe(e,h);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Pe.has(s)?r=Pe.get(s):(o=Se(s,h).map(ve),r=be(o),Pe.set(s,r))):n=e.trim();const i=n.split(f).map(ve);i.length>2&&ee(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${f}" — write "${i[0]}${f}${i.slice(1).join(",")}".${ae}`);const[a,c]=i,d=a.split(l).map(ve);return{propName:a,propSegments:d,propModifiers:c?c.split(",").map(ve):[],inFilters:r}}const Ne=new Map;function ke(e){const t=xe(e,h);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Ne.has(s)?r=Ne.get(s):(o=Se(s,h).map(ve),r=be(o),Ne.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&ee(`"${n}": the "@name" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount="...">) and read it by its path prefix instead.`);return{statePathName:n,statePathInfo:oe(n),outFilters:r}}const _e=new Set([b,"if","elseif","for",v]),Ae=new Set([I,N,k,P,x]);function Ce(e){const[...t]=function(e){return Se(e,";")}(e).map(ve).filter(e=>e.length>0),n=t.map(e=>{const t=e.indexOf(":");-1===t&&ee(`Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.`);const n=e.slice(0,t).trim(),o=e.slice(t+1).trim(),s=n.split(f)[0].split(h)[0].trim();if(s!==n&&_e.has(s)&&ee(`[wcs/binding-syntax] "${e}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${ae}`),n===b){o.length>0&&ee(`[wcs/binding-syntax] "${e}": "else" takes no value — write "else:".${ae}`);const t=oe("#else");return{propName:b,propSegments:[b],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===v){const t=ke(o);return t.outFilters.length>0&&ee(`Invalid spread binding "${e}": filters are not allowed on spread targets.`),0===t.statePathName.length&&ee(`Invalid spread binding "${e}": spread target path is required.`),{propName:v,propSegments:[v],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...ke(o),bindingType:n}}if("radio"===s||"checkbox"===s){const e=ke(o);return{...Ie(n),...e,bindingType:s}}{const e=ke(o),t=Ie(n);if(""===t.propSegments[0]&&t.propSegments.length>1){const o=t.propSegments.slice(1);return(o.includes("")||Ae.has(o[0]))&&ee(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...Ae].join(", ")}).${ae}`),{...t,propName:o.join(l),propSegments:o,...e,bindingType:"prop"}}return t.propSegments[0]===x||t.propSegments[0].startsWith($)?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>le.has(e.bindingType))&&ee(`[wcs/template-syntax] Invalid bindText: "${e}". 'if', 'elseif', 'else', and 'for' bindings must be single binding. Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).${ae}`)}return n}const Ee=new WeakMap,Me=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Oe=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Te(e){const t=Ee.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),s=Oe.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Me.has(r)?(Ee.set(e,s[2]),s[2]):null}function Re(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...ke(e),bindingType:"text"}}const je=new WeakMap,Le=new WeakSet;let We=0;async function De(e){const t=function(e){let t,n=je.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++We,promise:o,resolve:t},je.set(e,n),Le.has(e)&&n.resolve(),n}(e);await t.promise}function Be(e){const t=je.get(e);void 0===t?Le.add(e):t.resolve()}const ze=new WeakMap;function Fe(e){const t=ze.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{ze.set(e,n)}}function qe(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function Ve(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return qe(t);if(void 0!==n)return qe(n)}return qe(globalThis.customElements)}function He(e,t){e.upgrade?.(t)}function Ue(e){try{if(null===e||"object"!=typeof e&&"function"!=typeof e)return null;const t=e,n=t.addEventListener,o=t.removeEventListener,s=t.constructor?.wcBindable;if("function"!=typeof n||"function"!=typeof o)return null;if("wc-bindable"!==s?.protocol)return null;if(!Number.isInteger(s.version)||s.version<1)return null;const r=Xe(s.properties,Ge);if(null===r)return null;const i=void 0===s.inputs?new Map:Xe(s.inputs,Ke);if(null===i)return null;const a=void 0===s.commands?new Map:Xe(s.commands,Je);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Ge(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&("string"==typeof t.event&&0!==t.event.length&&(void 0===t.getter||"function"==typeof t.getter))}function Ke(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.attribute||"string"==typeof t.attribute)}function Je(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.async||"boolean"==typeof t.async)}function Xe(e,t){if(!Array.isArray(e))return null;const n=new Map;for(const o of e){if(!t(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function Qe(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:oe(n),inFilters:[],outFilters:[],bindingType:"prop"}}function Ye(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function Ze(e,t,n={}){const s=n.allowDeferred??!0;if(!t.some(e=>"spread"===e.bindingType))return t;const r=[],i=new WeakSet;for(const n of t){if("spread"!==n.bindingType){r.push(n);continue}e.nodeType!==Node.ELEMENT_NODE&&ee("Spread binding requires an element node.");const t=e,o=Fe(t);null===o&&ee(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=Ve(t);null===a&&ee(`CustomElementRegistry is unavailable for <${o}>.`);if(void 0===a.get(o)){s||ee(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}He(a,t);const l=Ue(t);null===l&&ee(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=new Set;for(const e of l.knownProperties.keys()){if(d.has(e))continue;d.add(e);const t=Qe(e,c);i.add(t),r.push(t)}for(const e of l.declaredInputs.keys()){if(d.has(e))continue;d.add(e);const t=Qe(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=Ye(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=Ye(r[t]);if(null!==n){if(a.get(n)===t)l.push(r[t]);else if(o.debug&&i.has(r[t])){const o=r[a.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 l.push(r[t])}return l}function et(e,t){let n=e;for(let e=0;e<t.length;e++){let o=t[e];for(n=n.firstChild;null!==n&&o>0;)n=n.nextSibling,o--;if(null===n)break}return n}function tt(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o];n.push({filterName:s.filterName,args:s.args,filterFn:pe(s.filterName,s.args,t,s.literals??s.args)})}return n}const nt=new WeakMap;function ot(e){return nt.get(e)||null}function st(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(o.bindAttributeName)}function rt(e){const t=[],n=e.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!st(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function it(e,t){for(let n=0;n<t.length;n++){const o=t[n];if(o!==e&&o.contains(e))return!0}return!1}function at(e){const t=[],n=rt(e),s=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!==Te(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const e=s.currentNode;n.length>0&&it(e,n)||t.push(e)}return t}const lt=new WeakSet;function ct(e,t,n,o){const s=Ze(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?Fe(e):null;return null===n&&ee("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}lt.add(e);const r=function(e,t){const n=[];for(const o of t){const t=tt(o.inFilters,"input"),s=tt(o.outFilters,"output");if("text"!==o.bindingType)n.push({...o,inFilters:t,outFilters:s,node:e,replaceNode:e});else{const r=e.nodeType===Node.TEXT_NODE?e:document.createTextNode("");n.push({...o,inFilters:t,outFilters:s,node:e,replaceNode:r})}}return n}(e,function(e,t){return void 0===t?e:e.map(e=>null!=e.uuid?e:t(e))}(s,o));return function(e,t){nt.set(e,t)}(e,r),Be(e),{bindings:r,deferred:null}}function dt(e,t){const n=at(e),o=[],s=[];for(const e of n){if(lt.has(e))continue;const n=ct(e,Pa(e),{allowDeferred:!0},t);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function ut(e){lt.add(e)}function ft(e){const{node:t,parseResults:n,transform:o}=e;!function(e){lt.delete(e)}(t);return ct(t,n,{allowDeferred:!1},o).bindings}const ht=new WeakMap;let pt=null;function mt(e){let t=e;for(;t;){const e=ht.get(t);if(e)return e;let n=t.parentNode;null===n&&null!==pt&&t instanceof ShadowRoot&&(n=pt(t)),t=n}return null}function gt(e,t){null!==t?ht.set(e,t):ht.delete(e)}let yt=null;const wt=new WeakMap;function bt(e){return wt.get(e)??[]}function vt(e,t){wt.set(e,t)}function $t(e){return wt.has(e)}const xt=new WeakMap;let St=null,Pt=0;function It(e){return xt.get(e)??[]}function Nt(e,t){null===St?xt.set(e,t):St.set(e,t)}function kt(){Pt++,null===St&&(St=new Map)}function _t(){if(0!==Pt&&(Pt--,!(Pt>0||null===St))){for(const[e,t]of St)xt.set(e,t);St=null}}function At(e){return(St?.has(e)??!1)||xt.has(e)}const Ct=Symbol("$$setLoopContext"),Et=Symbol("$$getByAddress"),Mt=Symbol("$$hasByAddress"),Ot=Symbol("$$setByAddress"),Tt=Symbol("$$connectedCallback"),Rt=Symbol("$$disconnectedCallback"),jt=Symbol("$$updatedCallback"),Lt=Symbol("$$errorCallback"),Wt=new WeakMap,Dt=new WeakMap;class Bt{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function zt(e,t){if(null===t){let t=Dt.get(e);return void 0!==t||(t=new Bt(e,null),Dt.set(e,t)),t}{let n=Wt.get(t);void 0===n&&(n=new WeakMap,Wt.set(t,n));let o=n.get(e);return void 0!==o||(o=new Bt(e,t),n.set(e,o)),o}}const Ft=new WeakMap;function qt(e,t){let n=Ft.get(e);void 0===n&&(n=new Map,Ft.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new Vt(e,t)),n.set(t,o)),o}class Vt{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function Ht(e,t){return zt(qt(e,t.pathInfo),t.listIndex)}function Ut(e,t,n){return zt(qt(e,t),n)}const Gt=new WeakMap;function Kt(e,t){null===t?Gt.delete(e):Gt.set(e,t)}function Jt(e){return Gt.get(e)||null}const Xt=new Map;function Qt(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=Xt.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,Xt.set(s,r),r}function Yt(e,t,n){return t<0||t>=n?null:e.at(t-n)}function Zt(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const en=new WeakMap;function tn(e){const t=mt(e.node);if(null===t)return null;let n=en.get(t);if(void 0===n)n=new WeakMap,en.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=Qt(t.pathInfo,e.statePathInfo);return n>0&&(o=Yt(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const nn=new WeakMap;function on(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=Jt(n);null===t?ee(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function sn(e,t){let n=null;if(n=nn.get(e)||null,null!==n)return n;const o=on(e,t),s=tn(e),r=ga(o);return null===r&&ee("No state tree found on this root for binding."),n=Ut(r,e.statePathInfo,s),nn.set(e,n),n}function rn(e){nn.delete(e)}const an=new WeakMap;function ln(e,t){const n=an.get(e);void 0===n?an.set(e,t):n instanceof Set?n.add(t):n!==t&&an.set(e,new Set([n,t])),null!==yt&&yt({type:"state:binding-added",absoluteAddress:e,binding:t})}function cn(e,t){const n=an.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&an.delete(e),null!==yt&&yt({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const dn=new WeakMap;function un(e){const t=an.get(e);return void 0!==t?t:null!==e.listIndex?dn.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const fn=new WeakMap,hn=new WeakMap;class pn{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]===c?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=mn(e,t)}}function mn(e,t){if(null===t){let t=hn.get(e);return void 0!==t||(t=new pn(e,null),hn.set(e,t)),t}{let n=fn.get(t);void 0===n&&(n=new WeakMap,fn.set(t,n));let o=n.get(e);return void 0!==o||(o=new pn(e,t),n.set(e,o)),o}}const gn=new WeakMap;function yn(e){let t=null;if(t=gn.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=tn(e);null===n&&ee(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=mn(e.statePathInfo,n)}else t=mn(e.statePathInfo,null);return gn.set(e,t),t}function wn(e){gn.delete(e)}function bn(){const e=new Map,t=new Map;return{add(n,o){let s=e.get(n);return void 0===s&&(s=new WeakSet,e.set(n,s)),!s.has(o)&&(s.add(o),t.set(n,(t.get(n)??0)+1),!0)},remove(n,o){const s=e.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(t.get(n)??1)-1;return r<=0?(e.delete(n),t.delete(n),!0):(t.set(n,r),!1)},has:(t,n)=>e.get(t)?.has(n)??!1,countOf:e=>t.get(e)??0,get keyCount(){return t.size},clear(){e.clear(),t.clear()}}}const vn=new Map,$n=bn();function xn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function Sn(e){let t="input";for(const n of e.propModifiers)n.startsWith($)&&(t=n.slice(2));return t}function Pn(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(g)){const o=Sn(e),s=xn(e,o);let r=vn.get(s);return void 0===r&&(t=e.statePathName,n=e.inFilters,r=e=>{const o=e.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("checkbox"!==o.type)return void console.warn("[@wcstack/state] event.target is not a checkbox input element.");const s=o.checked;let r=o.value;for(const e of n)r=e.filterFn(r);const i=ga(o.getRootNode());null===i&&ee("No state tree found on this root for two-way binding.");const a=mt(o);i.createState("writable",e=>{e[Ct](a,()=>{let n=e[t];if(Array.isArray(n))if(s)-1===n.indexOf(r)&&(e[t]=n.concat(r));else{const o=n.indexOf(r);-1!==o&&(e[t]=n.toSpliced(o,1))}else e[t]=s?[r]:[]})})},vn.set(s,r)),e.node.addEventListener(o,r),$n.add(s,e),!0}var t,n;return!1}function In(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function Nn(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)In(e)&&Promise.resolve(e).catch(e=>{console.error(`[wcstack/state] ${t} rejected.`,e)})}class kn{_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 _n extends kn{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==yt&&yt({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const An=new WeakMap;function Cn(e,t){let n=An.get(e);void 0===n&&(n=new Map,An.set(e,n));let o=n.get(t);return void 0===o&&(o=new _n(t,e),n.set(t,o)),o}const En=new WeakMap;function Mn(e){if(e.propSegments[0]!==x)return!1;const t=e.node,n=Fe(t),o=Ve(t);if(null!==n&&void 0===o?.get(n))return null===o&&ee(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(En.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||ee('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===Fe(e)?null:Ue(e)}(t);null===r&&ee(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&ee(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${ie(s,r.knownProperties.keys())}`);const a=i.event,l=e.statePathName,c=e.propModifiers,d=e=>{c.includes(p)&&e.preventDefault(),c.includes(m)&&e.stopPropagation();const n=ga(t.getRootNode());null===n&&ee("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||ee(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${ie(l,n.eventTokenNames)}${ae}`);const o=mt(t);n.createStateAsync("writable",async t=>{Nn(t[Ct](o,()=>{const s=null!==o?Zt(o.listIndex,o.pathInfo.wildcardCount):[];return Cn(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,d),En.set(e,{eventName:a,handler:d}),!0}class On extends kn{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==yt&&yt({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function Tn(e){return e instanceof On}const Rn=new Map,jn=bn();function Ln(e){const t=e.propModifiers.filter(e=>e===p||e===m).sort().join(",");return`${e.statePathName}::${t}`}const Wn=(e,t,n)=>o=>{t.includes(p)&&o.preventDefault(),t.includes(m)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=ga(r);null===i&&ee("No state tree found on this root for event handler.");const a=mt(s),l=e.startsWith(W+".");i.createStateAsync("writable",async t=>{const c=t[Ct](a,()=>{let c=null!==a?a.pathInfo.wildcardCount:0;if(null!==a){const e=i.addressHooks;if(e){const t=e.handlerScope;for(let e=0;e<t.length;e++)c=t[e](i,s,r,a,c)}}const d=null!==a?Zt(a.listIndex,c):[];if(l){const s=t[Et](mn(n,null));return Tn(s)||ee(`Event binding "${e}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...d)}const u=t[e];return"function"!=typeof u&&ee(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});Nn(c,`"${e}"`)})};function Dn(e){if(!e.propName.startsWith($))return!1;const t=Ln(e);let n=Rn.get(t);void 0===n&&(n=Wn(e.statePathName,e.propModifiers,e.statePathInfo),Rn.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),jn.add(t,e),!0}function Bn(e){if(!e.propName.startsWith($))return!1;const t=Ln(e),n=Rn.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==jn.countOf(t)&&(jn.remove(t,e)&&Rn.delete(t),!0)}const zn=new Map,Fn=bn();function qn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function Vn(e){let t="input";for(const n of e.propModifiers)n.startsWith($)&&(t=n.slice(2));return t}function Hn(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(g)){const o=Vn(e),s=qn(e,o);let r=zn.get(s);return void 0===r&&(t=e.statePathName,n=e.inFilters,r=e=>{const o=e.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("radio"!==o.type)return void console.warn("[@wcstack/state] event.target is not a radio input element.");if(!1===o.checked)return;let s=o.value;for(const e of n)s=e.filterFn(s);const r=ga(o.getRootNode());null===r&&ee("No state tree found on this root for two-way binding.");const i=mt(o);r.createState("writable",e=>{e[Ct](i,()=>{e[t]=s})})},zn.set(s,r)),e.node.addEventListener(o,r),Fn.add(s,e),!0}var t,n;return!1}const Un=new Set(["radio","checkbox"]),Gn=new Set(["value","valueAsNumber","valueAsDate"]);function Kn(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(Un.has(e)&&"checked"===t)return!0;if(Gn.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=Fe(n);if(null!==s){const e=Ve(n)?.get(s);void 0===e&&ee(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=Ue(n);if(o?.knownProperties.has(t))return!0}return!1}let Jn=1,Xn=1,Qn=1;const Yn=new WeakMap;function Zn(e,t,n){let o=Yn.get(e);void 0===o&&(o=new Map,Yn.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=Jn++,o.set(s,r)),r}function eo(e,t){return"to-element"===t?2*e:2*e+1}const to=new Set;function no(e){return{transactionId:Xn++,originBindingId:e,visitedEdges:to,hop:0}}function oo(e,t){const n=new Set(e.visitedEdges);return n.add(t),{transactionId:e.transactionId,originBindingId:e.originBindingId,visitedEdges:n,hop:e.hop+1}}let so=null;function ro(){return so}function io(e,t){const n=so;so=e;try{return t()}finally{so=n}}const ao=[];let lo=!1;const co=new Map,uo=bn(),fo=new WeakMap,ho=e=>e.detail,po=new WeakMap;function mo(e,t,n,o){const s=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.propName}::${e.statePathName}::${t}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function go(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=Fe(e.node);if(null!==n){const o=Ve(e.node)?.get(n);void 0===o&&ee(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Ue(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith($)&&(t=n.slice(2));return t}function yo(e){if(null!==Fe(e.node)){const t=Ue(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??ho}return null}function wo(e){if(null===Fe(e.node))return!1;const t=Ue(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}const bo=(e,t,n,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==s)l=s(i),s!==ho||r||function(e,t,n){const o=e[t];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${t} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,t)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${t}" key while element.${t} is ${typeof o}`),null===s)return;let r=po.get(e);void 0===r&&(r=new Set,po.set(e,r)),r.has(t)||(r.add(t),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${e.tagName.toLowerCase()}> "${t}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${t}, or (e) => e.target.${t}) on that wcBindable property.`))}(a,e,l);else{if(!(e in a))return void console.warn(`[@wcstack/state] Property "${e}" does not exist on target element.`);l=a[e]}let c=l;for(const e of n)c=e.filterFn(c);const d=fo.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(o.enablePropagationContext){const n=Zn(a,e,t),s=function(e,t){for(let n=ao.length-1;n>=0;n--){const o=ao[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,e);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:e,statePathName:t,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==yt&&yt({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:eo(n,"to-state"),node:a,member:e}));const r=eo(n,"to-state"),i=ro();if(null!==i&&i.visitedEdges.has(r))return void(null!==yt&&yt({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=oo(i??no(n),r)}const f=ga(a.getRootNode());null===f&&ee("No state tree found on this root for two-way binding.");const h=mt(a),p=()=>{r&&(lo=!0);try{f.createState("writable",e=>{e[Ct](h,()=>{e[t]=c})})}finally{r&&(lo=!1)}};null!==u?io(u,p):p()};const vo=new WeakSet;function $o(e){vo.add(e)}function xo(e){return!!vo.has(e)&&(vo.delete(e),!0)}const So=new WeakMap;function Po(e,t){const n=So.get(e);return!(void 0===n||n<t)&&(n===t?So.delete(e):So.set(e,n-t),!0)}const Io=new WeakSet;function No(e){Io.add(e)}function ko(e){return!!Io.has(e)&&(Io.delete(e),!0)}let _o=0;function Ao(){_o--}function Co(){return _o>0}class Eo{registry;entries=new Map;constructor(e){this.registry=e}wait(e,t,n=()=>{}){const o=e.toLowerCase();let s=this.entries.get(o);void 0===s&&(s={waiters:new Set},this.entries.set(o,s),this.registry.whenDefined(o).then(()=>this.settle(o,null),e=>this.settle(o,e)));const r={active:!0,resolve:t,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(e){return this.entries.get(e.toLowerCase())?.waiters.size??0}settle(e,t){const n=this.entries.get(e);if(void 0===n)return;this.entries.delete(e);const o=Array.from(n.waiters);n.waiters.clear();for(const e of o)e.active&&(e.active=!1,null===t?e.resolve():e.reject(t))}}const Mo=new WeakMap;function Oo(e){let t=Mo.get(e);return void 0===t&&(t=new Eo(e),Mo.set(e,t)),t}function To(e,t){let n=null;for(const o of e.propModifiers){const e=o.indexOf("=");if(e<0)continue;const s=o.slice(0,e).trim(),r=o.slice(e+1).trim();s!==y&&s!==w&&ee(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&ee(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function Ro(e){return e.propModifiers.some(e=>e.includes("="))}const jo=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Lo=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Wo(e,t){return"state"===e&&"call"===t?jo:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function Do(e){if(!o.enableDirectionalInitialSync)return Ro(e)&&ee("init=/sync= modifiers require enableDirectionalInitialSync."),jo;const t=null===(n=To(e,y))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:ee(`Invalid init modifier value "${n}".`);var n;const s=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":ee(`Invalid sync modifier value "${e}".`)}(To(e,w));if("event"===e.bindingType)return null!==t&&"none"!==t&&ee("Event bindings only allow init=none."),"call"===s?Lo:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(e.propSegments[0]===P)return Wo("state",s);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&ee(`Binding type "${e.bindingType}" does not support init=${t}.`),Wo(t??"state",s);const r=Ue(e.node);if(null===r)return Wo(t??"state",s);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||ee(`Property "${e.propName}" is not declared by wcBindable.`);const l=t??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||ee(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==s||i||ee(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}function Bo(e,t){return"auto"!==t?t:function(e){const t=ga(e.replaceNode.getRootNode());null===t&&ee("No state tree found on this root for binding.");const n=yn(e);let o=!1;return t.createState("readonly",e=>{o=e[Mt](n)}),o}(e)?"state":"element"}let zo=0,Fo=0;const qo=["active","disposed","failed"],Vo=new WeakMap,Ho=new WeakMap,Uo=new WeakMap,Go=new WeakMap,Ko=new WeakMap;function Jo(e,t){const n=Ko.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):Ko.set(e,new Set([n,t]))):Ko.set(e,t)}function Xo(e){return Ko.has(e)}function Qo(e,t){const n=Ko.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function Yo(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))Yo(n,t)}function Zo(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class es{root;observer;constructor(e){this.root=e;const t=globalThis.MutationObserver;this.observer="function"==typeof t?new t(e=>this.handleMutations(e)):null,this.observer?.observe(e,{childList:!0,subtree:!0})}handleMutations(e){const t=[],n=[];for(let o=0;o<e.length;o++){const s=e[o],r=s.removedNodes;if(0===r.length||!Po(s.target,r.length))for(let e=0;e<r.length;e++)t.push(r[e]);const i=s.addedNodes;for(let e=0;e<i.length;e++)n.push(i[e])}const o=[];for(const e of t)xo(e)||Yo(e,e=>{Qo(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)ko(e)&&!Co()||Yo(e,e=>{Qo(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&oa(o)}}const ts=new WeakMap;function ns(e){let t=ts.get(e);return void 0===t&&(t=new es(e),ts.set(e,t)),t}function os(e){const t=e.inFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|"),n=e.outFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.bindingType,e.propName,e.propModifiers.join(","),e.statePathName,t,n,e.uuid??""].join("\0")}function ss(e,t,n){const o=ga(on(e,n));null===o&&ee("No state tree found on this root for binding.");const s=qt(o,e.statePathInfo);return function(e,t,n){let o=dn.get(e);void 0===o&&(o=new WeakMap,dn.set(e,o));const s=o.get(t);void 0===s?o.set(t,n):s instanceof Set?s.add(n):s!==n&&o.set(t,new Set([s,n])),null!==yt&&yt({type:"state:binding-added",absoluteAddress:zt(e,t),binding:n})}(s,t,e),s}function rs(e,t){const n=sn(e,t);return ln(n,e),n}function is(e,t,n,o){null!==t?cn(t,e):function(e,t,n){const o=dn.get(e);if(void 0===o)return;const s=o.get(t);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(t),null!==yt&&yt({type:"state:binding-removed",absoluteAddress:zt(e,t),binding:n}))}(n,o,e),wn(e),rn(e)}function as(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class ls{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(e=null){null!==e&&this.observe(e)}initialize(e,t={},n){const o=t.registerAddress??!0,s={registerAddress:o,registerPathInfo:t.registerPathInfo??o,applyOnReconnect:t.applyOnReconnect??!0},r=[];for(const t of e){const e=this.remember(t,s),o=this.rowOf(e),i=null===o?-1:o.bindings.indexOf(e);if(null!==o&&0===o.phases[i]){const t=o;this.observe(e.replaceNode),s.registerAddress&&null===t.addresses[i]&&null===t.patternPathInfos[i]&&(t.registered=!0,this.registerRowSlot(t,i));continue}const a=Ho.get(e);void 0===a||"disposed"===a.phase||"failed"===a.phase?(this.start(e,s,n),r.push(e)):(this.observe(a.anchor),s.registerAddress&&null===a.address&&null===a.patternListIndex&&(a.options.registerAddress=!0,this.registerAddress(a)),"active"===a.phase&&this.settleInitialRecord(a),this.settleConnectedSnapshot(a))}return r.filter(e=>this.shouldApplyState(e))}activate(e,t){if(Zo(t)&&ns(t),null===this.rowPlan)for(const n of e){const e=Ho.get(n);if(void 0!==e&&e.session===this&&"disposed"!==e.phase&&"failed"!==e.phase){null===e.address&&null===e.patternListIndex&&(e.options.registerAddress=!0,this.registerAddress(e,t)),"active"===e.phase&&this.settleInitialRecord(e),this.settleConnectedSnapshot(e);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,t)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,e,t)}shouldApplyState(e){if(!o.enableDirectionalInitialSync)return Ro(e)&&Do(e),!0;const t=this.rowOf(e);if(null!==t){const n=t.bindings.indexOf(e);if(n>=0){if(!t.registered)return!0;if(2===t.phases[n])return!1;const e=t.plan.slots[n];return 1&t.flags[n]?"state"===e.authority||!e.policy.outputOnly:(t.flags[n]|=1,"state"===e.authority)}}const n=Ho.get(e);return void 0===n||n.session!==this||(!n.options.registerAddress||"waiting-definition"===n.phase||"failed"!==n.phase&&("active"===n.phase&&this.settleInitialRecord(n),n.initialApplyDone?"state"===n.resolvedAuthority||!n.outputOnlyMember&&!n.observationPending:(n.initialApplyDone=!0,"state"===n.resolvedAuthority)))}getRecord(e){const t=this.rowOf(e),n=null===t?-1:t.bindings.indexOf(e);if(null!==t&&n>=0)return{id:64*t.id+n,info:e,generation:t.generation,phase:qo[t.phases[n]],teardowns:null};const o=Ho.get(e);return o?.session===this?o:null}addTeardown(e,t){const n=Ho.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(as(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=Ve(e);null===s&&ee(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e),Jo(e,this);const r={node:e,active:!0,cancel:null};let i=this.deferredByNode.get(e);void 0===i&&(i=new Set,this.deferredByNode.set(e,i)),i.add(r),this.deferred.add(r);const a=()=>!!r.active&&(r.active=!1,i?.delete(r),this.deferred.delete(r),!0);return r.cancel=Oo(s).wait(t,()=>{if(a())try{He(s,e),n()}catch(e){o(e)}},e=>{a()&&o(e)}),()=>{a()&&r.cancel?.()}}disposeBinding(e){const t=this.rowOf(e);if(null!==t){const n=t.bindings.indexOf(e);if(n>=0)return void this.disposeRowSlot(t,n)}const n=Ho.get(e);void 0!==n&&n.session===this&&this.disposeRecord(n)}get isRowSession(){return null!==this.rowPlan}get currentRowPlan(){return this.rowPlan}disposeBindings(e){for(let t=0;t<e.length;t++)this.disposeBinding(e[t]);if(!(this.rows.size>0))for(const e of Array.from(this.deferred))e.active=!1,e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}destroyRow(e){const t=e.length>0?this.rowOf(e[0]):null;null!==t?(this.destroyRowRecord(t),this.rows.delete(t)):this.destroyRecords()}destroyRowRecord(e){for(let t=0;t<e.bindings.length;t++){const n=e.addresses[t];null!==n&&(cn(n,e.bindings[t]),e.addresses[t]=null),e.phases[t]=1}}dispose(){for(const e of Array.from(this.rows))for(let t=0;t<e.bindings.length;t++)this.disposeRowSlot(e,t);for(const e of Array.from(this.records))this.disposeRecord(e);for(const e of Array.from(this.deferred))e.active=!1,e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;if(0===this.records.size)return!0;for(const e of this.records)if(e.pendingDefinitions>0||e.observationPending)return!1;return!0}destroyRecords(){for(const e of this.rows)this.destroyRowRecord(e);this.rows.clear();for(const e of this.records)null!==e.address&&(cn(e.address,e.info),e.address=null),e.phase="disposed",e.teardowns=null;this.records.clear()}forEachActiveBindingNode(e){for(const t of this.rows)for(let n=0;n<t.bindings.length;n++)0===t.phases[n]&&e(t.bindings[n].node);for(const t of this.records)"active"===t.phase&&e(t.info.node)}rebindAddresses(){const e=[];for(const t of this.rows)for(let n=0;n<t.bindings.length;n++){if(0!==t.phases[n])continue;if(null===t.addresses[n]&&null===t.patternPathInfos[n])continue;const o=t.bindings[n];this.unregisterRowSlot(t,n),this.registerRowSlot(t,n),this.shouldApplyState(o)&&e.push(o)}for(const t of this.records){if("active"!==t.phase)continue;const n=t.info;if(null===t.address&&null===t.patternListIndex)continue;const o="for"===n.bindingType?sn(n):null;if(is(n,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null,this.registerAddress(t),null!==o){const e=sn(n);e!==o&&$t(o)&&vt(e,bt(o)),e!==o&&At(o)&&Nt(e,It(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return Zo(t)?t:null}(e);null!==t&&ns(t)}handleMutations(e,t,n){for(const n of t)Yo(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)Yo(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&oa(o)}handleRemovedNode(e){const t=this.knownBindingsByNode.get(e);if(void 0!==t)if(t instanceof Map)for(const e of t.values())this.disposeBinding(e);else this.disposeBinding(t);const n=this.deferredByNode.get(e);if(void 0!==n)for(const e of Array.from(n))e.active=!1,e.cancel?.(),n.delete(e),this.deferred.delete(e)}handleAddedNode(e,t){const n=this.knownBindingsByNode.get(e);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const e of o){const n=Ho.get(e);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(e);if(void 0!==o)try{this.start(e,o),o.applyOnReconnect&&this.shouldApplyState(e)&&t.push(e)}catch{}}}knownMapFor(e){const t=this.knownBindingsByNode.get(e);if(t instanceof Map)return t;const n=new Map;if(void 0!==t){let e=Go.get(t);void 0===e&&(e=os(t),Go.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;Jo(n,this);const o=this.knownMapFor(n);let s=Go.get(e);void 0===s&&(s=os(e),Go.set(e,s));const r=o.get(s);if(void 0!==r){const e=this.optionsByBinding.get(r);return void 0!==e&&(e.registerAddress||=t.registerAddress,e.registerPathInfo||=t.registerPathInfo,e.applyOnReconnect||=t.applyOnReconnect),r}return o.set(s,e),this.optionsByBinding.set(e,{...t}),e}initializeRow(e,t){this.rowPlan=e;const n=e.slots,o=t.length,s={id:++zo,session:this,generation:++Fo,plan:e,bindings:t,registered:!1,phases:new Array(o).fill(0),flags:new Array(o).fill(0),addresses:new Array(o).fill(null),patternPathInfos:new Array(o).fill(null),patternListIndexes:new Array(o).fill(null)};this.rows.add(s);for(let e=0;e<o;e++){const o=t[e],r=o.replaceNode;if(Jo(r,this),this.addKnownRowBinding(r,o,e),Vo.set(o,s),n[e].isEvent){try{Dn(o)}catch(t){throw s.phases[e]=2,t}s.flags[e]|=2}}}activatePlanRows(e,t,n){const o=t.length>0?this.rowOf(t[0]):null;if(null===o||o.bindings!==t){for(const e of t)this.initialize([e],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});return}o.registered=!0;const s=e.slots;let r=!1;for(let e=0;e<t.length;e++)if(0===o.phases[e])null===o.addresses[e]&&null===o.patternPathInfos[e]&&this.registerRowSlot(o,e,n);else{if(r||(o.generation=++Fo,r=!0,this.rows.add(o)),o.phases[e]=0,o.flags[e]=0,s[e].isEvent){try{Dn(t[e])}catch(t){throw o.phases[e]=2,this.runRowSlotTeardowns(o,e),t}o.flags[e]|=2}this.registerRowSlot(o,e,n)}}rowOf(e){const t=Vo.get(e);return void 0!==t&&t.session===this?t:null}registerRowSlot(e,t,n){if(null!==e.addresses[t]||null!==e.patternPathInfos[t])return;const o=e.bindings[t],s=tn(o);null!==s?(e.patternPathInfos[t]=ss(o,s,n),e.patternListIndexes[t]=s):e.addresses[t]=rs(o,n)}unregisterRowSlot(e,t){const n=e.addresses[t],o=e.patternPathInfos[t];null===n&&null===o||(is(e.bindings[t],n,o,e.patternListIndexes[t]),e.addresses[t]=null,e.patternPathInfos[t]=null,e.patternListIndexes[t]=null)}disposeRowSlot(e,t){if(1!==e.phases[t]){e.phases[t]=1,this.runRowSlotTeardowns(e,t);for(let t=0;t<e.phases.length;t++)if(0===e.phases[t])return;this.rows.delete(e)}}runRowSlotTeardowns(e,t){try{this.unregisterRowSlot(e,t)}catch{}if(2&e.flags[t]){e.flags[t]&=-3;try{Bn(e.bindings[t])}catch{}}}addKnownRowBinding(e,t,n){const o=this.knownBindingsByNode.get(e);if(void 0===o)return void this.knownBindingsByNode.set(e,t);if(o instanceof Map)return void o.set("@plan:"+n,t);const s=new Map;s.set("@plan:first",o),s.set("@plan:"+n,t),this.knownBindingsByNode.set(e,s)}start(e,t,n){!function(e){const t=e.node,n=e.replaceNode;t!==n&&null!==t.parentNode&&t.parentNode.replaceChild(n,t)}(e);const o=this.optionsByBinding.get(e)??{...t},s={id:++zo,info:e,generation:++Fo,phase:"discovered",teardowns:null,session:this,anchor:e.replaceNode,options:o,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:null,resolvedAuthority:null,initialSettled:!1,initialApplyDone:!1,outputOnlyMember:!1,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};Ho.set(e,s),this.records.add(s),void 0===n&&this.observe(s.anchor);try{s.phase="attaching",this.attachListeners(s),s.options.registerAddress&&this.registerAddress(s,n),0===s.pendingDefinitions&&(s.phase="active")}catch(e){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),e}}attachListeners(e){const t=e.info;Dn(t)?e.eventAttached=!0:t.propSegments[0]!==x?(Hn(t)&&as(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(g)){const t=Vn(e),n=qn(e,t),o=zn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Fn.countOf(n)&&(Fn.remove(n,e)&&zn.delete(n),!0))}return!1}(t)),Pn(t)&&as(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(g)){const t=Sn(e),n=xn(e,t),o=vn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==$n.countOf(n)&&($n.remove(n,e)&&vn.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(o.enableDirectionalInitialSync&&Kn(t.node,t.propName)&&-1===t.propModifiers.indexOf(g)){const n=function(e,t,n){let o=fo.get(e);void 0===o&&(o=new Map,fo.set(e,o));let s=o.get(t);return void 0===s&&(s=new Set,o.set(t,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(t),0===o?.size&&fo.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});as(e,n)}!function(e){const t=Fe(e.node);if(null!==t){const n=Ve(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&ee(`CustomElementRegistry is unavailable for <${t}>.`))}if(Kn(e.node,e.propName)&&-1===e.propModifiers.indexOf(g)){const t=go(e),n=yo(e),o=wo(e),s=mo(e,t,null!==n,o);let r=co.get(s);void 0===r&&(r=bo(e.propName,e.statePathName,e.inFilters,n,o),co.set(s,r)),e.node.addEventListener(t,r),uo.add(s,e)}}(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{Mn(t)&&as(e,()=>function(e){if(e.propSegments[0]!==x)return!1;const t=En.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),En.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=Fe(e.info.node);if(null===n)return void t();const o=Ve(e.info.node);if(null===o&&ee(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void t();e.phase="waiting-definition",e.pendingDefinitions+=1;const s=e.generation,r=Oo(o).wait(n,()=>{if(this.isAlive(e,s))try{He(o,e.info.node),t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e))}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))});as(e,r)}settleInitialRecord(e){if(o.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=Do(e.info),n=Bo(e.info,t.authority);if(e.initialPolicy=t,e.resolvedAuthority=n,e.initialSettled=!0,e.outputOnlyMember=t.outputOnly,e.phase="active",!t.observable)return;if("connect"===t.syncOn&&e.info.node instanceof HTMLElement&&!e.info.node.isConnected)return e.observationPending=!0,void _o++;this.readProducerSnapshot(e,"call"===t.syncOn)}catch(t){throw e.phase="failed",this.runTeardowns(e),this.records.delete(e),t}}}readProducerSnapshot(e,t){if(!this.isAlive(e,e.generation))return;const n=e.info.node,o=e.info.propName;if(!(o in n))return;const s=e.eventSequence,r=n[o];e.observationPending&&(e.observationPending=!1,Ao()),t&&e.eventSequence!==s||(e.hasProducerValue=!0,e.producerValue=r,"element"===e.resolvedAuthority&&function(e,t){let n=t;for(const t of e.inFilters)n=t.filterFn(n);const o=ga(e.node.getRootNode());null===o&&ee("No state tree found on this root for initial binding sync.");const s=mt(e.node);o.createState("writable",t=>{t[Ct](s,()=>{t[e.statePathName]=n})})}(e.info,r))}settleConnectedSnapshot(e){if(o.enableDirectionalInitialSync&&e.observationPending&&e.info.node instanceof HTMLElement&&e.info.node.isConnected)try{this.readProducerSnapshot(e,!1)}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}}registerAddress(e,t){if(null!==e.address||null!==e.patternListIndex)return;const n=e.info,o=tn(n);if(null!==o?(e.patternPathInfo=ss(n,o,t),e.patternListIndex=o):e.address=rs(n,t),!e.options.registerPathInfo)return;const s=ga(n.replaceNode.getRootNode());null===s&&ee("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(e,t){return e.generation===t&&Ho.get(e.info)===e&&"disposed"!==e.phase&&"failed"!==e.phase}disposeRecord(e){"disposed"!==e.phase&&(e.phase="disposed",this.runTeardowns(e),this.records.delete(e))}runTeardowns(e){e.observationPending&&(e.observationPending=!1,Ao());const t=e.info;if(null!==e.address||null!==e.patternListIndex)try{is(t,e.address,e.patternPathInfo,e.patternListIndex),e.address=null,e.patternPathInfo=null,e.patternListIndex=null}catch{}if(e.twowayAttached){e.twowayAttached=!1;try{!function(e){const t=Fe(e.node);if(null!==t){const n=Ve(e.node),o=n?.get(t);if(void 0===o)return}if(Kn(e.node,e.propName)&&-1===e.propModifiers.indexOf(g)){const t=go(e),n=mo(e,t,null!==yo(e),wo(e)),o=co.get(n);if(void 0===o)return;e.node.removeEventListener(t,o),uo.remove(n,e)&&co.delete(n)}}(t)}catch{}}if(null!==e.teardowns){const t=Array.from(e.teardowns).reverse();e.teardowns=null;for(const e of t)try{e()}catch{}}if(e.eventAttached){e.eventAttached=!1;try{Bn(t)}catch{}}}}function cs(e){let t=Uo.get(e);return void 0===t&&(t=new ls(e),Uo.set(e,t)),t}function ds(e){return Ho.get(e)?.session??Vo.get(e)?.session??null}let us=null;function fs(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const hs=Object.freeze([]);const ps=new WeakMap;const ms=new WeakMap;function gs(e){return ms.get(e)??[]}function ys(e,t){ms.set(e,t)}const ws=new WeakMap;function bs(e){return ws.get(e)??[]}function vs(e,t){ws.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 $s=0;function xs(){return`u${($s++).toString(36)}`}let Ss=0,Ps=0;const Is=Symbol("wcs.listIndex.noValue");class Ns{uuid=xs();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;constructor(e,t,n){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=Is,this._index=t,this._version=Ss,this._chainGeneration=Ps}get index(){return this._index}set index(e){this._index=e,this._version=++Ss,this.indexes[this.position]=e}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}get value(){return this._value}set value(e){this._value=e}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=Ss),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===Ps||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=Ps),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++Ss,Ps++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function ks(e,t,n=e){return new Ns(e,t,n)}function _s(e,t){e.reparent(t)}function As(e){return e.homeParentListIndex}function Cs(e,t){e.value=t}function Es(e,t){const n=e.value;return n!==Is&&n===t.value}const Ms=new WeakMap,Os=new WeakSet;function Ts(e){return Os.has(e)}function Rs(e,t){const n=As(e),o=e.parentListIndex;return null===n||n===o||Os.has(n)?function(e,t,n){return null!==e&&null!==n&&n!==t&&!!Os.has(e)&&!Os.has(n)&&n.position===e.position&&Es(n,e)}(n,o,t)||function(e,t){return e!==t&&null!==e&&null!==t&&e.position===t.position&&Os.has(e)&&!Os.has(t)}(o,t)?t:null:n}function js(e){const t=Ms.get(e);return void 0===t?null:t}function Ls(e,t){const n=Ms.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o){const e=Rs(o,t);if(null!==e)for(const t of n)_s(t,e)}return n}function Ws(e,t){null!==t?Ms.set(e,t):Ms.delete(e)}const Ds=new WeakMap;function Bs(e,t){null===t?Ds.delete(e):Ds.set(e,t)}function zs(e){const t=Ds.get(e);t&&(t.dirty=!0)}const Fs=Symbol.for("wcstack.transition-runner");function qs(e){const t=globalThis[Fs];return null==t||"wcs-transition-runner"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.run?null:"function"==typeof t.accepts&&t.accepts(e)?t:null}function Vs(e,t,n){const o=qs(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const Hs=[],Us=[];function Gs(e){Us.includes(e)||Us.push(e)}function Ks(e,t=0){const n=Hs.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?Hs.push(o):Hs.splice(n,0,o)}function Js(e){queueMicrotask(()=>{throw e})}class Xs{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){for(let t=0;t<Us.length;t++)Us[t](e);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:e,context:t}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(e){const t=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(e),t&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){kt(),queueMicrotask(()=>{const e=this._queueUpdateRecords,t=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],this._applyChange(e,t)})}hasQueuedPath(e,t){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===e&&n.absoluteAddress.absolutePathInfo.pathInfo.path===t)}testApplyChange(e,t){this._applyChange(e.map((e,n)=>({absoluteAddress:e,context:t?.[n]??null})))}_applyChange(e,n=[]){const o=new Map,s=new Set;for(let t=0;t<e.length;t++){const n=e[t],r=o.get(n.absoluteAddress);null!==yt&&null!=r&&null!==n.context&&r.transactionId!==n.context.transactionId&&yt({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:r.transactionId,winnerTransactionId:n.context.transactionId}),o.set(n.absoluteAddress,n.context),s.add(n.absoluteAddress)}for(let e=0;e<n.length;e++){const t=n[e];o.has(t)||o.set(t,null)}const r=[],i=new Map;o.forEach((e,t)=>{if(null!==e&&e.hop>=32)return console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:t.absolutePathInfo.pathInfo.path,transactionId:e.transactionId,hop:e.hop,maxHops:32}),void(null!==yt&&yt({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop}));const n=un(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(r.push(t),null!==e&&i.set(t,e));else!1!==n.replaceNode.isConnected&&(r.push(n),null!==e&&i.set(n,e))});try{const e=()=>{i.size>0?oa(r,i):oa(r)};if(t()||0===r.length)e();else{const t=Vs("state",e);void 0!==t&&t.catch(Js)}}finally{_t(),function(e){for(const t of Hs.slice())t.listener(e)}(s)}}}const Qs=new Xs;function Ys(){return Qs}const Zs=new WeakMap,er=new WeakMap,tr=new WeakMap,nr=new WeakMap;let or=!1;const sr=new WeakMap,rr=new WeakMap,ir=new WeakMap,ar=[];function lr(e,t){const n=cr(e);if(n.recorded.has(t))return;n.recorded.add(t);const o=oe(t).cumulativePaths;if(o.length<2)return;let s=ir.get(e);void 0===s&&ir.set(e,s=new Map);for(let e=0;e<o.length-1;e++){let n=s.get(o[e]);void 0===n&&s.set(o[e],n=new Set),n.add(t)}}function cr(e){let t=Zs.get(e);return void 0===t&&Zs.set(e,t={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),t}function dr(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function ur(e,t,n){const o=e.get(t);o.delete(n),0===o.size&&e.delete(t)}function fr(e,t,n,o){const s=function(e,t){let n=e.byPath.get(t);return void 0===n&&e.byPath.set(t,n=new Map),n}(e,t);let r=er.get(o);if(void 0===r&&er.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(ur(s,e,o),r.set(t,n),dr(s,n,o)),!1}return r.set(t,n),dr(s,n,o),!0}function hr(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function pr(e,t,n,o,s,r){e.lastValue.set(t,n),s&&(null!==o.listIndex&&hr(tr,o.listIndex,r),null!==r.levelListIndex&&hr(nr,r.levelListIndex,r))}function mr(e,t,n,o,s){or=!0;const r=cr(e);lr(e,t);pr(r,t,s,o,fr(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function gr(e,t){cr(e).tracked.add(t)}function yr(e,t,n){if("number"!=typeof t)return;const o=e.indexes[t];if(void 0!==o)for(const t of e.getters)n.push(Ht(e.stateElement,mn(t,o)))}function wr(e,t){if(void 0!==e)for(const n of e)t.push(n)}function br(e,t,n,o,s){const r=Zs.get(e),i=r?.byPath.get(t),a=sr.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return ar;const l=r.lastValue.has(t),c=r.lastValue.get(t);r.lastValue.set(t,s);const d=[],u=!n||!Object.is(o,s),f=l&&(!n||!Object.is(c,o))&&!Object.is(c,s);if(void 0!==i&&(n&&wr(i.get(o),d),f&&wr(i.get(c),d),u&&wr(i.get(s),d)),void 0!==a)for(const e of a)n&&yr(e,o,d),f&&yr(e,c,d),u&&yr(e,s,d);return d}function vr(e,t){let n=e;for(const e of t){if("object"!=typeof n||null===n)return;n=n[e]}return n}function $r(e,t,n){const o=Zs.get(e).byPath.get(t);if(void 0!==o)for(const e of o.values())wr(e,n);const s=sr.get(e)?.get(t);if(void 0!==s)for(const e of s)for(let t=0;t<e.indexes.length;t++)yr(e,t,n)}function xr(e){const t=nr.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function Sr(e){if(!or)return;const t=tr.get(e);if(void 0!==t){tr.delete(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=er.get(o),r=s.get(n);s.delete(n),ur(Zs.get(t).byPath.get(n),r,o),null!==e.levelListIndex&&xr(e)}}}function Pr(e,t,n){if(!or)return;const o=nr.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=Zs.get(e),i=o.byPath.get(s);ur(i,t,r),dr(i,n,r),er.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(zs(r),Ys().enqueueAbsoluteAddress(r,null))}}const Ir=new WeakMap,Nr=Object.freeze([]),kr=new Set;function _r(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:Nr,s=Array.isArray(n)&&n.length>0?n:Nr,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Nr,o=Array.isArray(t)&&t.length>0?t:Nr;let s=Ir.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Ls(o,e)||[],a=i.length>0?As(i[0]):e;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:kr,deleteIndexSet:new Set(i),addIndexSet:kr};let t=Ls(s,e);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=ks(e,n,a);t.push(o)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:kr,deleteIndexSet:kr,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 l={oldIndexes:i,newIndexes:i,changeIndexSet:kr,deleteIndexSet:kr,addIndexSet:kr};if(null!==t)return function(e,t){const n=new Set(t),o=new Set(e),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let t=0;t<e.length;t++)a.set(e[t],t);for(let e=0;e<t.length;e++){const n=t[e];r.has(n)||a.get(n)!==e&&s.add(n)}return{oldIndexes:e,newIndexes:t,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,t);t=[];const n=new Map;for(let e=0;e<o.length;e++){const t=o[e];let s=n.get(t);s||(s=[],n.set(t,s)),s.push(e)}const r=new Set,c=new Set;for(let o=0;o<s.length;o++){const l=s[o],d=n.get(l),u=d&&d.length>0?d.shift():void 0;if(void 0===u){const n=ks(e,o,a);t.push(n),c.add(n)}else{const e=i[u];u!==o&&r.add(e),t.push(e)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:c}}finally{void 0!==l&&(!function(e,t,n){let o=Ir.get(e);o||(o=new WeakMap,Ir.set(e,o)),o.set(t,n)}(o,s,l),Ws(s,l.newIndexes))}}(e,t,n);!function(e,t){for(let n=0;n<e.length;n++){if(e[n].index!==n){const t=e[n].index;e[n].index=n,Pr(e[n],t,n)}Cs(e[n],t[n])}}(o.newIndexes,Array.isArray(n)&&n.length>0?n:Nr),function(e){for(const t of e)Os.add(t)}(o.deleteIndexSet);for(const e of o.deleteIndexSet)Sr(e);return function(e){for(const t of e)Os.delete(t)}(o.newIndexes),function(e,t){if(!or||e===t)return;const n=rr.get(e);if(void 0===n)return;rr.delete(e);const o=rr.get(t);rr.set(t,void 0===o?n:o.concat(n));for(const o of n){o.indexes=t;const n=cr(o.stateElement).lastValue.get(o.path);if("number"!=typeof n)continue;const s=e[n],r=t[n];if(s!==r)for(const e of[s,r])if(void 0!==e&&!Ts(e))for(const t of o.getters){const n=Ht(o.stateElement,mn(t,e));zs(n),Ys().enqueueAbsoluteAddress(n,null)}}}(o.oldIndexes,o.newIndexes),o}function Ar(e){if(0===e.changeIndexSet.size||e.addIndexSet.size===e.newIndexes.length)return null;const t=new Map;for(let n=0;n<e.oldIndexes.length;n++)t.set(e.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of e.newIndexes){if(e.addIndexSet.has(i))continue;const a=t.get(i);if(void 0===a)return null;a<s&&(r=!1),s=a,n.push(i),o.push(a)}if(r)return null;const i=function(e){const t=e.length,n=[],o=new Array(t).fill(-1);for(let s=0;s<t;s++){const t=e[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;e[n[o]]<t?r=o+1:i=o}r>0&&(o[s]=n[r-1]),n[r]=s}const s=[];let r=n.length>0?n[n.length-1]:-1;for(;r>=0;)s.push(r),r=o[r];return s.reverse(),s}(o),a=new Set;for(const e of i)a.add(n[e]);return a}const Cr=new WeakSet;const Er=new WeakMap;function Mr(e){return Er.get(e)??null}function Or(e,t){Er.set(e,t)}const Tr=new WeakMap;function Rr(e){return Tr.get(e)??[]}function jr(e,t){Tr.set(e,t)}function Lr(e,t){const n=Rr(e);for(const e of n)gt(e,t)}const Wr=new WeakMap;const Dr=new WeakMap;function Br(e,t){for(let n=0;n<e.length;n++)if(t.has(e[n]))return!0;return!1}function zr(e,t,n,o,s){const r=function(e,t,n){let o=Dr.get(e);void 0===o&&Dr.set(e,o=new Map);const s=o.get(n);if(void 0!==s)return s;const r=n+".",i=t.map((t,o)=>{const s=e.slots[o];if(s.isEvent||s.isIndexBinding)return null;const i=t.statePathInfo.path;if(!i.startsWith(r))return null;const a=i.slice(r.length).split("."),l=[];let c=n;for(const e of a){if("*"===e)return null;c+="."+e,l.push(c)}return{tail:a,prefixes:l}});return o.set(n,i),i}(e,t,o.pathInfo.path),i=s.stateElement.getterPaths;let a,l=!1;for(let e=0;e<t.length;e++){const c=t[e];if(!n.shouldApplyState(c))continue;const d=r[e];if(null===d||Br(d.prefixes,i)){ta(c,s);continue}if(s.appliedBindingSet.has(c))continue;s.appliedBindingSet.add(c),l||(a=s.state[Et](o),l=!0);const u=d.tail;let f=a;for(let e=0;e<u.length;e++){if(null==f){f=void 0;break}f=f[u[e]]}ea(c,s,f)}}function Fr(e,t,n){Lr(e,t);const o=gs(e),s=Mr(e);if(null!==s&&(s.activate(o,n.rootNode),null!==t&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(e){return Wr.get(e)??null}(e);if(null!==r)return void zr(r,o,s,t,n)}for(const e of o){if(null===s){ln(sn(e),e)}(null===s||s.shouldApplyState(e))&&ta(e,n)}}function qr(e){if(!e.mounted)return;const t=gs(e),n=Mr(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{cn(sn(o),o)}}!function(e){const t=Rr(e);for(let e=0;e<t.length;e++)gt(t[e],null)}(e)}function Vr(){return Object.freeze(new Set)}const Hr=new WeakMap,Ur=Vr();function Gr(e,t){const n=Hr.get(e);n?n.add(t):Hr.set(e,new Set([t]))}function Kr(e){const t=Hr.get(e);return void 0!==t?t:Ur}function Jr(e,t){const n=Hr.get(e);n&&(n.delete(t),0===n.size&&Hr.delete(e))}function Xr(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o];n.push({filterName:s.filterName,args:s.args,filterFn:pe(s.filterName,s.args,t,s.literals??s.args)})}return n}function Qr(e){return{...e,inFilters:Xr(e.inFilters,"input"),outFilters:Xr(e.outFilters,"output")}}const Yr=new Set(["if","elseif","else","for"]);class Zr{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(e,t=!1){this._content=e,this._ranged=t;const n=[];for(let t=e.firstChild;null!==t;t=t.nextSibling)n.push(t);this._childNodeArray=n,this._firstNode=this._childNodeArray.length>0?this._childNodeArray[0]:null,this._lastNode=this._childNodeArray.length>0?this._childNodeArray[this._childNodeArray.length-1]:null}get firstNode(){return this._firstNode}get lastNode(){return this._lastNode}get mounted(){return this._mounted}appendTo(e){const t=this._childNodeArray;for(let n=0;n<t.length;n++){const o=t[n];No(o),e.appendChild(o)}this._mounted=!0}_movableNodes(){if(!this._ranged||!this._mounted)return this._childNodeArray;const e=this._firstNode,t=this._lastNode;if(null===e||null===t||null===e.parentNode)return this._childNodeArray;const n=[];for(let o=e;null!==o;o=o.nextSibling)if(n.push(o),o===t)return n;return this._childNodeArray}mountAfter(e){const t=e.parentNode;if(t){let n=e;for(const e of this._movableNodes()){if(n.nextSibling!==e){No(e);const o=t;e.parentNode===t&&"function"==typeof o.moveBefore?o.moveBefore(e,n.nextSibling):t.insertBefore(e,n.nextSibling)}n=e}}this._mounted=!0}tryDestroy(){const e=Mr(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRow(gs(this));const t=this._childNodeArray;for(let e=0;e<t.length;e++){const n=t[e];null!==n.parentNode&&($o(n),n.parentNode.removeChild(n))}const n=gs(this);for(let e=0;e<n.length;e++){const t=n[e];Yr.has(t.bindingType)&&Kr(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const e=Mr(this);null!==e&&(e.isRowSession?e.disposeBindings(gs(this)):e.dispose())}this._teardownBindings()}_teardownBindings(){const e=gs(this);for(let t=0;t<e.length;t++){const n=e[t];Yr.has(n.bindingType)&&Kr(n.node).forEach(e=>{e.unmount()}),wn(n),rn(n)}}unmount(){{const e=Mr(this);null!==e&&(e.isRowSession?e.disposeBindings(gs(this)):e.dispose())}for(const e of this._childNodeArray)null!==e.parentNode&&($o(e),e.parentNode.removeChild(e));const e=gs(this);for(let t=0;t<e.length;t++){const n=e[t];Yr.has(n.bindingType)&&Kr(n.node).forEach(e=>{e.unmount()}),wn(n),rn(n)}this._mounted=!1}}function ei(e){let t=e.topLevelStructural;return void 0===t&&(t=e.topLevelStructural=function(e){const t=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.commentElsePrefix}):`);for(let n=e.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&t.test(n.data))return!0;return!1}(e.fragment)),t}function ti(e){const t=document.createDocumentFragment(),n=new Zr(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 ni(e,t,n){const o=document.importNode(t.fragment,!0),s=t.nodeInfos,r=new Array(s.length);for(let e=0;e<s.length;e++){const t=et(o,s[e].nodePath);null===t&&ee(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),ut(t),Be(t),r[e]=t}const i=n.slots,a=new Array(i.length),l=[];for(let e=0;e<i.length;e++){const t=i[e],n=r[t.nodeIndex],o={...t.template,node:n,replaceNode:n};a[e]=o,t.isIndexBinding&&l.push(o)}const c=function(e,t,n){let o=ra.get(n);void 0!==o&&o.currentRowPlan===e||(o=new ls,ra.set(n,o));return o.initializeRow(e,t),o}(n,a,e.node),d=new Zr(o);return Or(d,c),ys(d,a),function(e,t){Wr.set(e,t)}(d,n),vs(d,l),jr(d,r),Gr(e.node,d),d}function oi(e){void 0!==e.uuid&&null!==e.uuid||ee("BindingInfo.uuid is null.");const n=Sa(e.uuid);n||ee(`Fragment with UUID "${e.uuid}" not found.`);const s=!t()&&ei(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(e){const t=o.enableDirectionalInitialSync,n=[],s=e.nodeInfos;for(let t=0;t<s.length;t++){const o=s[t],r=et(e.fragment,o.nodePath);if(null===r)return null;for(const e of o.parseBindTextResults){const o=e.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=e.propSegments[0];if(s===P||s===x)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Fe(r))return null;if("prop"===o&&Kn(r,e.propName))return null;const i=Qr(e);let a;try{a=Do({...i,node:r,replaceNode:r})}catch{return null}if(a.observable||"auto"===a.authority)return null;n.push({nodeIndex:t,template:i,isEvent:"event"===o,isIndexBinding:e.statePathName in A,policy:a,authority:a.authority})}}return{directional:t,slots:n}}(n)),null!==r)return ni(e,n,r);const i=document.importNode(n.fragment,!0),a=function(e,t){const[n,o]=function(e,t){const n=[],o=[];for(const s of t){const t=et(e,s.nodePath);if(null===t&&ee(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),lt.has(t))continue;const r=ct(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new ls,r=s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:r,bindingSession:s}}(i,n.nodeInfos);s&&function(e,t){e.appendChild(document.createComment(`wcs-row-end:${t}`))}(i,e.uuid);const l=new Zr(i,s);Or(l,a.bindingSession),ys(l,a.bindingInfos);const c=[];for(const e of a.bindingInfos)e.statePathName in A&&c.push(e);return vs(l,c),jr(l,a.nodes),Gr(e.node,l),l}const si=new WeakSet,ri=Symbol.for("wcstack.state.view-transition-naming");function ii(){const e=qs("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function ai(e,t,n){const o=function(e){const t=e.firstNode;if(null===t)return null;const n=e.lastNode;for(let e=t;null!==e;e=e.nextSibling){if(e.nodeType===Node.ELEMENT_NODE)return e;if(e===n)break}return null}(e);if(null===o||si.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[ri]??={counter:0,assigned:0,warned:!1}}();r.assigned>=n.limit?r.warned||(r.warned=!0,console.warn(`[@wcstack/state] auto view-transition-name limit (${n.limit}) reached; further elements are left unnamed. Raise naming-limit on <wcs-view-transition>, or switch to naming="manual" and name only what should morph.`)):(si.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${t}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${t}`))}const li=new WeakMap,ci=new WeakMap,di=new WeakMap,ui=new WeakMap;function fi(e,t,n){!function(e,t,n){let o=ci.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,ci.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function hi(e,t){li.set(e,t)}function pi(e){return e.nodeType===Node.ELEMENT_NODE||(e.nodeType===Node.TEXT_NODE?""!==(e.textContent?.trim()??""):e.nodeType===Node.COMMENT_NODE&&e.data.startsWith("@@wcs-"))}function mi(e,t){if(null===t)return!1;if(e.nextSibling===t)return!0;const n=e.compareDocumentPosition(t);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}function gi(e,t,n){if(o=t,!Cr.has(o))return null;var o;let s=null;for(let t=0;t<n.newIndexes.length;t++){const o=n.newIndexes[t],r=n.oldIndexes[t],i=n.addIndexSet.has(o)&&n.deleteIndexSet.has(r)?e.get(r):void 0;void 0!==i&&(s??={byAddedIndex:new Map,reused:new Set},s.byAddedIndex.set(o,i),s.reused.add(i))}return s}const yi=new Set(["if","elseif","else","for"]);function wi(e,t){for(const n of gs(e))if(t.appliedBindingSet.delete(n),yi.has(n.bindingType))for(const e of Kr(n.node))wi(e,t)}function bi(e){for(const t of gs(e)){if(!yi.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of Kr(t.node))bi(n),e&&n.mounted&&(qr(n),n.unmount(),Jr(t.node,n))}}function vi(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function $i(e,n,s){const r=Boolean(s);let i;const a=Kr(e.node);i=0===a.size?oi(e):a.values().next().value;const l=t(),c=e.uuid??"",d=e.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${vi(e)}`),qr(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${vi(e)}`),l){const t=document.createComment(`@@wcs-${d}-start:${c}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),i.mountAfter(t);const n=document.createComment(`@@wcs-${d}-end:${c}:${e.statePathName}`),o=i.lastNode??t;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(e.node);Fr(i,mt(e.node),n);const t=ii();null!==t&&ai(i,"branch",t)}}const xi=new WeakMap;function Si(e){return xi.get(e)??[]}const Pi=new Set;const Ii=Symbol.for("wcstack.trustedTypes.policy");function Ni(){const e=globalThis[Ii];return null===e||"object"!=typeof e?null:e}let ki;let _i=!1;function Ai(e,t){if(_i)return;if(!function(){if(void 0!==ki)return ki;if(!("trustedTypes"in globalThis))return ki=!1,ki;try{document.createElement("div").innerHTML="<i></i>",ki=!1}catch{ki=!0}return ki}())return;_i=!0;const n="function"==typeof Ni()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/state deliberately does not pass state values through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/state] Writing to "${t}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${n}\nInstall a sanitizing policy before the first binding is applied:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr bind the value as text instead of HTML. See docs/csp.md section 7.`,{element:e,property:t})}const Ci={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")}},Ei=new Set(["textContent","innerText","innerHTML"]);function Mi(e,n,s){if(void 0===s&&1===e.propSegments.length&&Ei.has(e.propSegments[0])&&(s=""),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 c=i[0],d=r[c];if(d!==s){null!==us&&null!==d&&"object"==typeof d&&null!==s&&"object"==typeof s&&null!==Fe(r)&&us.rememberOverwrittenObject(r,c,d);const t="innerHTML"===(l=c)||"outerHTML"===l||"srcdoc"===l,i=()=>{let e=!1;try{r[c]=t?function(e){if("string"!=typeof e)return e;const t=Ni(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(s):s,e=!0}catch(e){t&&Ai(r,c),o.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:e})}if(e){const e=function(e,t){const n=Fe(e);if(null===n)return null;const o=Ve(e)?.get(n);if(void 0===o)return null;const s=Ue(e)?.declaredInputs.get(t);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==e)try{!function(e,t,n){if(null==n)return void e.removeAttribute(t);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);e.setAttribute(t,o)}(r,e,s)}catch(t){o.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:s,error:t})}}};if(o.enablePropagationContext&&Kn(r,c)){const t=Zn(r,c,e.statePathName),o=eo(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??ro()??no(t);if(a.visitedEdges.has(o))null!==yt&&yt({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const e=oo(a,o);io(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:Qn++,writtenValue:n};ao.push({receipt:i,node:e});try{return r()}finally{ao.pop()}}(r,c,s,t,e.transactionId,i))}}else i()}if(t()){const e=Ci[c];e?e(r,s):(!function(e,t,n){let o=xi.get(e);o||(o=[],xi.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,c,s),a=r,Pi.add(a))}return}var a,l;const c=i[0];let d=r[c];for(let e=1;e<i.length-1;e++){const t=i[e];if(null==d)return;d=d[t]}const u=i[i.length-1],f=d[u];if(f!==s){if(Object.isFrozen(d))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:f,newValue:s}));null!==us&&2===i.length&&"object"==typeof d&&null!==d&&null!==Fe(r)&&(u in d?us.rememberOverwrittenValue(r,c,u,d[u]):us.recordInjectedKey(r,c,u));try{d[u]=s}catch(e){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:f,newValue:s,error:e})}}}const Oi=new WeakSet;function Ti(e,t,n){}function Ri(e,t){let n=e;for(;null!==n&&n!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e;n=Object.getPrototypeOf(n)}}function ji(e,t,n){const o=function(e){const t=[];let n=e;for(;null!==n&&n!==Object.prototype;){for(const e of Object.getOwnPropertyNames(n))t.push(e);n=Object.getPrototypeOf(n)}return t}(e),s=t.length>0?t+l:"";for(const e of n){if(s.length>0&&!e.startsWith(s))continue;const t=e.slice(s.length);t.length>0&&-1===t.indexOf(l)&&o.push(t)}return o}const Li={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},Wi={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Di(e,t,n,o){return`[wcs/index-arity] ${e}("${t}") requires ${"$resolve"===e?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${ae}`}function Bi(e,t){return`[wcs/recursion-anchor] "${e}" does not match the declared recursion anchor "${t}". This version supports exactly one anchor per state, and "**" must be followed by a well-formed suffix (no second "**", no empty segment, no bare "*" right after "**").`}function zi(e,t){return`$setAll("${e}") ${t}`}function Fi(e,t,n){return`[wcs/wildcard-rank] ${e} needs ${t} enclosing loop level(s) but the current scope provides ${n}. Wrap it in that many "for" templates, or use $resolve(path, indexes) to name the row explicitly.${ae}`}function qi(e,t){const n=yn(t);if(n.pathInfo.path in A){const e=mt(t.node);return null===e&&ee(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&ee("ListIndex not found for loopContext:");const n=A[t];void 0===n&&ee(`Invalid index name: ${t}`);const o=Yt(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&ee(Fi(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[Et](n)}const Vi=new WeakSet;function Hi(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const Ui=Object.freeze({[I]:function(e,t,n){const o=e.node,s=e.propSegments[1];"boolean"!=typeof n&&ee("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[N]:function(e,t,n){const o=e.node,s=e.propSegments[1];null!=n?o.getAttribute(s)!==n&&o.setAttribute(s,n):o.hasAttribute(s)&&o.removeAttribute(s)},[k]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[P]:function(e,t,n){Tn(n)||ee("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=ps.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||ee('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=Fe(e);if(null===t)return null;const n=Ve(e)?.get(t);return void 0===n&&ee(`Custom element <${t}> is not defined for command binding.`),Ue(e)}(r);null===a&&ee(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||ee(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${ie(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),ps.delete(e));const l=new WeakRef(r);let c=null;c=o.subscribe((...t)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void ps.delete(e);const o=n[i];return"function"!=typeof o&&ee(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),ps.set(e,{token:o,unsubscribe:c,elementRef:l})}}),Gi={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!Oi.has(e.replaceNode)){Oi.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=tn(e),i=sn(e),a=bt(i),l=a.length>0&&!ci.has(e.node)?[]:a,d=_r(r,l,o);n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]);let u=ci.get(e.node);const f=void 0!==u?gi(u,l,d):null,h=Array.isArray(l)&&l.length===d.deleteIndexSet.size&&d.deleteIndexSet.size>0;if(h&&null===f&&null!==e.node.parentNode){let t=ui.get(e.node);if(void 0===t){const n=li.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(pi(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(pi(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n),ui.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){So.set(e,(So.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let p=h?1e3-function(e){return di.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;if(void 0!==u){const t=u;d.deleteIndexSet.forEach(n=>{const o=t.get(n);void 0!==o&&(null!==f&&f.reused.has(o)?(qr(o),bi(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?Jr(e.node,o):(qr(o),o.unmount(),function(e,t){let n=di.get(e.node);void 0===n&&(n=[],di.set(e.node,n)),n.length<1e3?n.push(t):Jr(e.node,t)}(e,o),p-=1),h||t.delete(n))}),h&&(ci.delete(e.node),u=void 0)}let m=e.node;const g=oe(s.path+"."+c),y=n.stateElement.loopContextStack,w=Ar(d);let b=null;d.newIndexes.length==d.addIndexSet.size&&d.newIndexes.length>0&&m.isConnected&&null===f&&(b=document.createDocumentFragment(),Kt(b,n.rootNode));const v=t(),$=ii(),x=e.uuid??"",S=di.get(e.node);for(const t of d.newIndexes){let o;if(d.addIndexSet.has(t)){const r=mn(g,t);if(y.createLoopContext(r,r=>{if(o=f?.byAddedIndex.get(t)??(void 0!==S?S.pop():void 0),void 0===o?o=oi(e):wi(o,n),null!==b)v&&b.appendChild(document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`)),o.appendTo(b),v&&b.appendChild(document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`));else{if(m.nextSibling!==o.firstNode){if(v){const e=document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`);m.parentNode.insertBefore(e,m.nextSibling),m=e}o.mountAfter(m)}if(v){const e=document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`),n=o.lastNode??m;n.parentNode.insertBefore(e,n.nextSibling)}}Fr(o,r,n),null!==$&&ai(o,"row",$)}),void 0===o&&ee(`Content not found for ListIndex: ${t.index} at path "${s.path}"`),null!==f&&f.reused.has(o)){const e=n.stateElement.addressHooks;if(e){const t=e.rowReused;for(let e=0;e<t.length;e++)t[e](n.stateElement,o)}}}else{if(o=void 0!==u?u.get(t)??null:null,d.changeIndexSet.has(t)){const e=bs(o);for(const t of e)ta(t,n)}null===o&&ee(`Content not found for ListIndex: ${t.index} at path "${s.path}"`);const e=!o.mounted;if(null!==w&&w.has(t)&&mi(m,o.firstNode)||m.nextSibling===o.firstNode||o.mountAfter(m),e){const e=o,s=mn(g,t);y.createLoopContext(s,t=>{Fr(e,t,n)})}}m=o.lastNode||m,void 0===u&&(u=new WeakMap,ci.set(e.node,u)),u.set(t,o)}li.set(e.node,m),null!==b&&(e.node.parentNode.insertBefore(b,e.node.nextSibling),Kt(b,null))},if:$i,else:$i,elseif:$i,radio:function(e,t,n){const o=e.node,s=fs(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=fs(o.value,e.inFilters),r=Array.isArray(n)?n:hs;o.checked=r.includes(s)}},Ki=new WeakMap,Ji=new WeakMap,Xi=new WeakMap;function Qi(){}function Yi(e){const t=us;if(null!==t){const n=e.replaceNode,o=e.propSegments[0];if(t.isComplete(n,o))return Ti;if(t.isDeclared(n,o))return Qi}return Mi}function Zi(e,t){ea(e,t,qi(t.state,e))}function ea(e,t,n){const o=fs(n,e.outFilters);if(!0===Ji.get(e))return void t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement});let s=Ki.get(e);if(void 0===s){if(Ki.has(e))return s=Yi(e),s===Ti&&Ki.set(e,s),void s(e,t,o);if(s=Gi[e.bindingType],void 0===s){const t=e.propSegments[0];if(s=Ui[t],Ki.set(e,s),void 0===s){Fe(e.replaceNode)?(s=Yi(e),s===Ti&&Ki.set(e,s)):(s=Mi,Ki.set(e,s))}}if(s===Mi){if("SELECT"===e.node.tagName){const n=e.propSegments[0];if("value"===n||"selectedIndex"===n)return t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement}),void Ji.set(e,!0)}}s(e,t,o)}else s(e,t,o)}function ta(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=sn(e);if(t.updatedAbsAddressSetByStateElement.has(t.stateElement)){t.updatedAbsAddressSetByStateElement.get(t.stateElement).add(n)}else t.updatedAbsAddressSetByStateElement.set(t.stateElement,new Set([n]))}const n=ds(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==Xi.get(e)){const t=Fe(e.replaceNode);if(t&&void 0===Ve(e.replaceNode)?.get(t))return void function(e,t){if(Vi.has(e))return;Vi.add(e);const n=()=>{Vi.delete(e);const t=ds(e);(null===t||t.shouldApplyState(e))&&oa([e])},o=n=>{Vi.delete(e),Hi(t,n)},s=ds(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{Vi.delete(e),r()})||(Vi.delete(e),r()))}const r=Ve(e.replaceNode);if(null===r)return Vi.delete(e),void Hi(t,new Error("CustomElementRegistry is unavailable."));Oo(r).wait(t,()=>{e.replaceNode.isConnected?n():Vi.delete(e)},o)}(e,t);Xi.set(e,!0)}if(!0===t.sameRootVerified)return void Zi(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Jt(o),null===o&&ee("Root node for fragment not found for binding.")),o!==t.rootNode){const n=ga(o);null===n&&ee("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:t.appliedBindingSet,newListValueByAbsAddress:t.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:t.updatedAbsAddressSetByStateElement,deferredSelectBindings:t.deferredSelectBindings};Zi(e,r)})}else Zi(e,t)}function na(e,t,n,o){if(null!==n&&!0===n.hasErrorCallback){const s={path:e.statePathName,bindingType:e.bindingType,node:e.node},r=o.get(n);void 0===r?o.set(n,[{error:t,info:s}]):r.push({error:t,info:s})}else console.error(`[@wcstack/state] binding "${e.bindingType}: ${e.statePathName}" failed to apply; the rest of this batch continues.`,{node:e.node,error:t});null!==yt&&yt({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function oa(e,t,n){let s=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;s<e.length;){let n=e[s];if(!1===n.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),s++;continue}let d=n.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=Jt(d),null===d&&ee("Root node for fragment not found for binding."));const u=ga(d);null===u&&ee("No state tree found on this root for binding."),u.createState("readonly",o=>{const f={rootNode:d,stateElement:u,state:o,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:t};for(;;){try{ta(n,f)}catch(e){na(n,e,u,c)}s++;const t=e[s];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;n=t}})}for(const{binding:e,value:n,stateElement:o}of l)try{Mi(e,{propagationContextByBinding:t},n)}catch(t){na(e,t,o??null,c)}for(const[e,t]of i.entries())vt(e,t),Nt(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[jt](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[Lt](n,o)}catch(e){console.error(`[@wcstack/state] $errorCallback threw while handling the failure of binding "${o.bindingType}: ${o.path}".`,{error:e,original:n,node:o.node})}})}function sa(e,t,n){const[o,s,r]=dt(e,n),i=cs(e);for(const e of o)gt(e,t);oa(i.initialize(s)),function(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=ft(o);0!==e.length&&(gt(o.node,t),oa(n.initialize(e)))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}(r,t,i)}const ra=new WeakMap;async function ia(e){const t=e.querySelectorAll(o.tagNames.state),n=[],s=Ve(e);null===s&&ee(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const e of t){if(st(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function aa(e){if(e===document)await ia(document),Y(document),Ba(document,document),sa(document.body,null);else{const t=e;t.host.hasAttribute(o.bindAttributeName)&&await De(t.host),await ia(t),Y(t),Ba(t,t),sa(t,null)}}const la={watch:"temporal",scan:"temporal",stream:"temporal",scopes:"scopes",dcc:"scopes",bindComponent:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function ca(e,t){return`[wcs/feature-not-installed] ${t} needs the "${e}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${la[e]??e}" before the state is defined.`}let da=null;function ua(e){return null===da&&ee(ca("ssr",e)),da}const fa=new WeakMap,ha=new WeakMap,pa=new Set,ma=[];function ga(e){return fa.get(e)??null}function ya(e){return ha.get(e)??Promise.resolve()}const wa=new WeakSet;function ba(e){wa.add(e)}function va(e,n){const s=fa.get(e);if(null===n){if(void 0===s)return;fa.delete(e),pa.delete(s),null!==yt&&yt({type:"state:element-unregistered",rootNode:e,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;if(void 0===s){const o=!t()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===e.constructor.name||"Document"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{if(o){await ua('the "enable-ssr" attribute').hydrate(e)||await aa(e)}else await aa(e);ba(e),Ua(),t()}catch(e){n(e)}})});ha.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await aa(e),ba(e),Ua(),t()}catch(e){n(e)}})});ha.set(e,t)}}void 0!==s&&ee('A state tree is already registered on this root — one <wcs-state> per root in v2. This second element stays unregistered: it keeps the state it loaded and its declarations stay live, but nothing binds to it and disconnecting it runs no cleanup — remove it. Mount additional states onto the tree instead: <wcs-state mount="...">.'),fa.set(e,n),pa.add(n);for(let t=0;t<ma.length;t++)ma[t](e,n);null!==yt&&yt({type:"state:element-registered",rootNode:e,element:n}),o.debug&&console.debug("State element registered",n)}}const $a=new Map;function xa(e,t,n){if(null===n)$a.delete(e);else{$a.set(e,n);const o=ga(t);null===o&&ee("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const e of n.nodeInfos)for(const t of e.parseBindTextResults)o.setPathInfo(t.statePathName,t.bindingType)}}function Sa(e){return $a.get(e)||null}function Pa(e){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=Ce(t.getAttribute(o.bindAttributeName)||"");return t.localName===o.tagNames.state&&t.hasAttribute("mount")?n.filter(e=>e.propSegments[0]!==S):n}if(e.nodeType===Node.COMMENT_NODE){const t=Te(e);null===t&&ee("Comment node binding text not found.");const n=Sa(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Re(t),s=null):s=t,[{...o,uuid:s}]}return[]}let Ia;function Na(){return Ia??={filterName:"not",args:[]}}const ka=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function _a(e,t){const n=t+l+c,o=e.indexOf("|");let s,r;if(-1!==o?(s=e.slice(0,o).trim(),r=e.slice(o)):(s=e.trim(),r=""),"."===s)s=n;else{if(!s.startsWith("."))return e;s=n+l+s.slice(1)}return r.length>0?s+r:s}function Aa(e,t){const n=ka.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+_a(s,t)+r}function Ca(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=_a(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function Ea(e,t){return Ca(e,t)}function Ma(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=Aa(n.data,t);continue}const o=e;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const e=Ca(r,t);e!==r&&o.setAttribute(n,e)}}}function Oa(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 Ta(e){const t=[],n=at(e);for(const e of n){const n=Pa(e);let o=e;if(e.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==e.parentNode){const t=document.createTextNode("");e.parentNode.replaceChild(t,e),o=t}t.push({nodePath:Oa(o),parseBindTextResults:n})}return t}function Ra(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 ja=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),La=Na();function Wa(e,t){const n=t.outFilters;return{...t,outFilters:[...n,La],bindingType:e}}function Da(e,t,n,o,s,r=!0){Ra(t),"string"==typeof o&&Ma(t,o),Ba(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Ta(t)};return void 0!==s&&function(e,t,n){for(const o of e)for(let e=0;e<o.parseBindTextResults.length;e++){const s=o.parseBindTextResults[e];null==s.uuid&&(o.parseBindTextResults[e]=t(s,n))}}(i.nodeInfos,s,o),i}function Ba(e,t,n,s){const r=o.commentElsePrefix,i=rt(t),a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode(e){const t=e;if(i.length>0&&-1!==i.indexOf(t))return NodeFilter.FILTER_REJECT;if("template"===t.tagName.toLowerCase()){if((t.getAttribute(o.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let l=null;const c=[],d=[];for(;a.nextNode();){const e=a.currentNode;d.push(e)}for(const t of d){let i=t.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=Ea(i,n));let a=Ce(i)[0];const d=ja.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=xs();let p=null;const m="for"===u?a.statePathName:n;if("else"===u){null===l&&ee("'else' binding found without preceding 'if' or 'elseif' binding."),a=Wa("else",l.parseBindTextResult),p=Da(e,f,a,m,s,!1),xa(h,e,p);const n=c.at(-1),o=document.createComment(`@@${d}:${h}`);void 0!==n?(t.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:Oa(o),parseBindTextResults:Pa(o)})):t.replaceWith(o)}else if("elseif"===u){null===l&&ee("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Da(e,f,a,m,s),xa(h,e,p);const n=document.createComment(`@@${d}:${h}`),o=xs(),i={fragment:document.createDocumentFragment(),parseBindTextResult:Wa("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Oa(n),parseBindTextResults:Pa(n)}),xa(o,e,i);const u=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==u?(t.remove(),u.fragment.appendChild(g),u.nodeInfos.push({nodePath:Oa(g),parseBindTextResults:Pa(g)})):t.replaceWith(g)}else{p=Da(e,f,a,m,s),xa(h,e,p);const n=document.createComment(`@@${d}:${h}`);t.replaceWith(n)}"if"===u?(c.length=0,l=p):"elseif"===u?l=p:"else"===u&&(l=null,c.length=0)}}const za=()=>`[${o.bindAttributeName}]`;function Fa(e){if(Xo(e))return!0;if(!qa(e))return!1;if(e.hasAttribute(o.bindAttributeName))return!1;const t=e.querySelector(za());return null!==t&&Xo(t)}function qa(e){return 1===e.nodeType}function Va(e){if(Fa(e))return;Y(e),Ba(e.getRootNode(),e);const t=e.hasAttribute(o.bindAttributeName),n=e.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);sa(t&&s?n:e,null)}const Ha=[];function Ua(){const e=Ha.splice(0,Ha.length);for(const t of e)Va(t);a()}const Ga={protocol:"wcs-binder",version:1,bind:function(e){var t;qa(e)&&!Fa(e)&&(t=e.getRootNode(),wa.has(t)?Va(e):Ha.push(e))}};const Ka="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Ja=0;async function Xa(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++Ja}\n`;let s=!1;const r=e=>{e.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{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}`)}}catch(e){throw new Error(function(e,t,n){const o=t?.message??String(t);return n?`The inline <script> of state "${e}" was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL, so script-src must allow blob:. Prefer moving the state into an external file and loading it with src="./state.js", which requires no extra CSP directive. See ${Ka}`:`Failed to evaluate the inline <script> of state "${e}": ${o}. If this page sets a Content-Security-Policy, see ${Ka}`}(t,e,s),{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function Qa(e){try{const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}catch(e){ee(`Failed to load script file: ${e}`)}}class Ya{_loopContextStack=Array(u).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&ee("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=u&&ee("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&&ee("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&&ee("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else n.listIndex.length!==n.pathInfo.wildcardCount&&ee(`Cannot push loop context when there is no active loop context: the list index chain (length ${n.listIndex.length}) does not cover the wildcard path (wildcard count ${n.pathInfo.wildcardCount}).`);let s;this._loopContextStack[this._length]=n,this._length++;try{s=t(n)}finally{s instanceof Promise?s.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return s}}const Za=new WeakMap;function el(e,t){let n=Za.get(e);void 0===n&&(n=new Map,Za.set(e,n));let o=n.get(t);return void 0===o&&(o=new On(t,e),n.set(t,o)),o}const tl=new WeakMap;function nl(e){const t=tl.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 el(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:el(e,n)}},set(){ee("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){ee("$command namespace is read-only; deleting from it is not allowed.")}});return tl.set(e,n),n}const ol=Symbol("wcs.notHandled"),sl=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],rl=new Map;function il(e,t){rl.set(e,t)}const al=new Map;let ll=[],cl=[];function dl(e,t){al.set(e,t),ll=Array.from(al.values()).sort((e,t)=>e.order-t.order),cl=ll.slice().reverse()}function ul(e,t){for(let n=0;n<ll.length;n++)ll[n].activate?.(e,t)}function fl(e){"readonly"===e.mutability&&ee("This state is readonly.")}const hl=new Map;class pl{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(e){const t=e.split("."),n=t.slice();let o=0,s=0,r=0,i="none";const a=[];for(let e=0;e<t.length;e++){const i=t[e];if("*"===i)n[e]="*",a.push(null),o++,r++;else{const t=Number(i);Number.isNaN(t)||(n[e]="*",a.push(t),s++,r++)}}const l=oe(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=e,this.segments=t,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function ml(e){let t;return hl.get(e)??(hl.set(e,t=new pl(e)),t)}function gl(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?null:Yt(n.listIndex,o,n.pathInfo.wildcardCount)}function yl(e,t){if(!e.untracking&&e.addressStackLength>0){const n=e.lastAddressStack,o=n?.pathInfo??null,s=e.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==t.pathInfo.path&&(s.addDynamicDependency(t.pathInfo.path,o.path),t.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const e=Qt(t.pathInfo,o);if(e>0){let r=!1;const i=t.listIndex??null,a=n.listIndex??null;for(let n=0;n<e;n++){if((null!==i?Yt(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?Yt(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}function wl(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function bl(e,t,n,o,s){const r=e.addressHooks;if(r){const i=r.readMissing;for(let r=0;r<i.length;r++){const a=i[r](e,t,n,o,s);if(a!==ol)return a}}return ol}function vl(e,t,n,o,s){if(t.pathInfo.segments[0]===W)return function(e,t){let n=e;for(let e=1;e<t.length;e++){if(Object(n)!==n)return;n=Reflect.get(n,t[e])}return n}(nl(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){if(null===t.parentAddress){const r=bl(s,t,null,n,o);if(r!==ol)return r;ee(function(e,t,n){return`[${Li.binding}] Path "${e}" does not exist on the state tree.${ie(e,ji(t,"",n))}${ae}`}(t.pathInfo.path,e,s.getterPaths))}const r=xl(e,t.parentAddress,n,o);if(null==r)return;const i=t.pathInfo.segments[t.pathInfo.segments.length-1],a=s.addressHooks;if(a&&0!==a.readMissing.length&&i!==c&&!(i in Object(r))){const e=bl(s,t,Object(r),n,o);if(e!==ol)return e}if(i===c){const e=t.listIndex?.index??ee(Fi(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.get(r,e)}return Reflect.get(r,i)}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 $l(e,t,n,o,s){const r=Ht(s,t),i=function(e){return Ds.get(e)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=vl(e,t,n,o,s);return Bs(r,{value:l,dirty:!1,generation:a}),l}function xl(e,t,n,o){yl(o,t),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,t.pathInfo);const s=o.stateElement,r=s.addressHooks;if(r){const e=r.read;for(let r=0;r<e.length;r++){const i=e[r](s,t,n,o);if(i!==ol)return i}}return wl(s,t)?$l(e,t,n,o,s):vl(e,t,n,o,s)}function Sl(e,t,n,o,s,r){const i=new Map,a=(o,s,r,l,c,d,u)=>{const f=o[s]??null;if(null===f)return void u.push(d);const h=mn(f,r),p=Ht(n.stateElement,h),m=It(p),g=xl(e,h,t,n),y=_r(r,m,g).newIndexes,w=l[c]??null;if(i.set(p,g),null===w)for(let e=0;e<y.length;e++){const t=y[e];a(o,s+1,t,l,c+1,d.concat(t.index),u)}else{const e=y[w]??ee(`ListIndex not found at index ${w} of ${f.path}`);s+1<o.length?a(o,s+1,e,l,c+1,d.concat(e.index),u):u.push(d.concat(e.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[e,t]of i.entries())Nt(e,Array.isArray(t)?t:[]);return l}function Pl(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Ls(xl(e,mn(a,r),t,n),r);null==l&&ee(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??ee(`ListIndex not found at index ${c} of ${a.path}`)}return r}function Il(e,t,n,o){"object"==typeof e&&null!==e||ee(`${U} list "${t}": ${n} row at index ${o} must be a plain object (got ${null===e?"null":typeof e}).`);const s=Object.getPrototypeOf(e);s!==Object.prototype&&null!==s&&ee(`${U} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function Nl(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&ee(`${U} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function kl(e,t,n,o){const s=new Array(e.length),r=new Set;for(let i=0;i<e.length;i++){const a=e[i];Il(a,n,o,i);const l=Nl(a,t,n,o,i);r.has(l)&&ee(`${U} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function _l(e,t){const n=[];for(const o of Object.keys(t))Object.is(e[o],t[o])||n.push({field:o,value:t[o]});for(const o of Object.keys(e))Object.hasOwn(t,o)||null==e[o]||n.push({field:o,value:null});return n}function Al(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=xl(e,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=t.pathInfo.lastSegment;if(i===c){const e=t.listIndex?.index;return"number"==typeof e&&e in r}return i in r}const Cl=new WeakMap;function El(e,t){null===t?Cl.delete(e):Cl.set(e,t)}function Ml(e,t,n){const s=mn(oe(e.wildcardParentPaths[t]),n),r=Ht(e.stateElement,s),i=It(r),a=e.stateProxy[Et](s),l=_r(s.listIndex,i,a);e.observedListValueByAbsAddress.set(r,Array.isArray(a)?a:[]);const 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}`),[]}}(l,e.searchType);if(t===e.wildcardPaths.length-1)e.targetListIndexes.push(...c);else for(const n of c)Ml(e,t+1,n)}const Ol=[];function Tl(e,t,n,o,s){return"full"===e.listExpansion||e.stateElement.crossRowListPaths?.has(t)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?e.keyedMergePath===t?{fullRows:Ol,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:Ol,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Rl=[];function jl(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Rl;let s=null;const r=t+l;for(const e of o){if(e!==t&&!e.startsWith(r))continue;const o=oe(e);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??Rl}function Ll(e,t,n){const o=t.pathInfo.path,s=e.staticMap.get(o);if(s)for(const r of s){const s=oe(r);if(e.listPathSet.has(o)&&s.lastSegment===c){const i=e.stateProxy[Et](t),a=Ht(e.stateElement,t),l=It(a),c=_r(t.listIndex,l,i);e.observedListValueByAbsAddress.set(a,Array.isArray(i)?i:[]);const d=Tl(e,o,0,0,c);for(const t of d.fullRows){const o=mn(s,t);e.result.add(o),n.push(o)}if(null!==d.movedRows){const t=jl(e,r,s);if(null===t)for(const t of d.movedRows){const o=mn(s,t);e.result.add(o),n.push(o)}else if(t.length>0)for(const o of d.movedRows)for(const s of t){const t=mn(s,o);e.result.add(t),n.push(t)}}}else{const o=mn(s,t.listIndex);e.result.add(o),n.push(o)}}const r=e.dynamicMap.get(o);if(r)for(const o of r){const s=oe(o),r=[];if(s.wildcardCount>0){const n=Qt(t.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&ee(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=Yt(t.listIndex,n-1,t.pathInfo.wildcardCount)):o=null;const i={stateElement:e.stateElement,observedListValueByAbsAddress:e.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};Ml(i,n,o),r.push(...i.targetListIndexes)}else{null===t.listIndex&&ee(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=Yt(t.listIndex,n-1,t.pathInfo.wildcardCount);r.push(e)}}else r.push(null);for(const t of r){const o=mn(s,t);e.result.add(o),n.push(o)}}}function Wl(e,t,n,o,s,r,i,a,l){const c=t.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(t),[];const d=function(e,t,n,o){const s=new Map,r=new Map,i=[e];for(r.set(e,0);i.length>0;){const e=i.pop();if(s.has(e))continue;const o=t.get(e),a=n.get(e);let l;l=void 0===o?a??[]:void 0===a?o:o.concat(a),s.set(e,l);for(let e=0;e<l.length;e++){const t=l[e];r.set(t,(r.get(t)??0)+1),s.has(t)||i.push(t)}}const a=new Map,l=new Set,c=[];for(const[e,t]of r)0===t&&(a.set(e,0),l.add(e),c.push(e));for(let e=0;e<c.length;e++){const t=c[e],n=a.get(t)+1;n>o&&ee(`Maximum dependency depth of ${o} exceeded. Possible circular dependency detected at path: ${t}`);const i=s.get(t);for(let e=0;e<i.length;e++){const t=i[e];n>(a.get(t)??-1)&&a.set(t,n);const o=r.get(t)-1;r.set(t,o),0===o&&(l.add(t),c.push(t))}}if(l.size!==s.size){let e=-1;for(const t of l){const n=a.get(t);n>e&&(e=n)}const t=e+1;for(const e of s.keys())l.has(e)||a.set(e,t)}return a}(c,n,o,1e3),u={ranks:d,stateElement:e,observedListValueByAbsAddress:new Map,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null};!function(e,t,n){const o=[],s=e.ranks,r=(e,t)=>{let n=s.get(e.pathInfo.path)??t;n<t&&(n=t),(o[n]??=[]).push(e)};r(t,0);const i=[];for(let t=0;t<o.length;t++){const s=o[t];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!e.visited.has(a)){e.visited.add(a),n(a),i.length=0,Ll(e,a,i);for(let e=0;e<i.length;e++)r(i[e],t+1)}}}}(u,t,a);for(const[e,t]of u.observedListValueByAbsAddress)Nt(e,t);return Array.from(u.result)}function Dl(e,t,n,o,s){const r=e.addressHooks;if(r){const i=r.writeObserve;for(let r=0;r<i.length;r++)i[r](e,t,n,o,s)}}function Bl(e,t,n){const o=e.addressHooks;if(o){const s=o.written;for(let o=0;o<s.length;o++)s[o](e,t,n)}}function zl(e,t,n){const o=e.addressHooks;if(o){const s=o.swapped;for(let o=0;o<s.length;o++)s[o](e,t,n)}}function Fl(e,t,n,s,r,i){const a=function(e,t){return!0===Zs.get(e)?.byPath.has(t)||!0===sr.get(e)?.has(t)}(e,t),l=function(e,t){return!0===ir.get(e)?.has(t)}(e,t);if(!a&&!l)return;const d=Ys(),u=o.enablePropagationContext?ro()??null:null,f=e=>{zs(e),d.enqueueAbsoluteAddress(e,u)};a&&br(e,t,n,s,r).forEach(f),l&&function(e,t,n,o){const s=oe(t).segments.length,r=[];for(const i of ir.get(e).get(t)){const t=oe(i).segments.slice(s);if(t.includes(c))$r(e,i,r);else for(const s of br(e,i,!0,vr(n,t),vr(o,t)))r.push(s)}return r}(e,t,n?s:i(),r).forEach(f)}function ql(e,t,n,s,r,i,a="diff"){const l=o.enablePropagationContext?ro()??no(-1):null,c=Ys();c.enqueueAbsoluteAddress(t,l),i&&zs(t),Wl(s.stateElement,e,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",t=>{if(t===e)return;const n=Ht(s.stateElement,t);zs(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function Vl(e,t,n,o,s){s&&(e.getterPaths.has(t)?zs(n):Bs(n,{value:o,dirty:!1,generation:e.stateGeneration}))}function Hl(e,t,n,o,s,r,i,a){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,o);const i=xl(e,n,s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===c){const e=t.listIndex?.index??ee(Fi(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.set(i,e,o)}return Reflect.set(i,a,o)}if(!r.stateElement.setterPaths.has(t.pathInfo.path))return Reflect.set(e,t.pathInfo.path,o);r.pushAddress(t),r.beginUntrack();try{return Reflect.set(e,t.pathInfo.path,o,s)}finally{r.endUntrack(),r.popAddress()}}finally{ql(t,n,s,r,i,a)}}function Ul(e,t,n,o,s,r,i,a){const d=t.parentAddress??ee(`address.parentAddress is undefined path: ${t.pathInfo.path}`),u=xl(e,d,s,r)??[];let f=(h=u,Cl.get(h)??null);var h;if(null===f){const e=js(u)??[];f={value:[...u],listIndexes:[...e]},El(u,f)}try{return Hl(e,t,n,o,s,r,i,a)}finally{const n=f.value.indexOf(o),i=xl(e,d,s,r)??[],a=Array.isArray(i)?js(i)??[]:[],h=t.listIndex.index,p=-1!==n?f.listIndexes[n]:ks(d.listIndex,-1);a[h]=p;if(new Set(i).size===f.value.length){for(let e=0;e<a.length;e++)a[e].index=e;El(u,null),function(e,t,n,o,s,r){const i=r.stateElement,a=Ys(),d=Ht(i,e);bt(d)===n&&(Ws(t.value,t.listIndexes),vt(d,t.value),function(e){Cr.add(e)}(t.value));a.enqueueRenderOnlyAddress(d);const u=new Map;t.listIndexes.forEach((e,t)=>u.set(e,t));const f=oe(e.pathInfo.path+l+c);for(let e=0;e<o.length;e++){const n=o[e],l=u.get(n);if(l===e)continue;const c=mn(f,n),d=Ht(i,c);if(void 0===l){const n=Ut(i,f,t.listIndexes[e]??null);zl(i,d,n),ql(c,d,s,r,null,wl(i,c),"full");continue}Wl(i,c,i.staticDependency,i.dynamicDependency,i.listPaths,s,"new",e=>{const t=Ht(i,e);zs(t),a.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}}(d,f,i,a,s,r)}}}function Gl(e,t,n,o,s){const r=s.stateElement.listKeys;if(null!=r&&Array.isArray(n)){const i=r.get(t.pathInfo.path);if(void 0!==i){const r=xl(e,t,o,s),a=function(e,t,n,o){const s=kl(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=kl(r,t,e,"current"),a=new Map;for(let e=0;e<r.length;e++)a.set(i[e],r[e]);const l=new Array(o.length),c=[];for(let e=0;e<o.length;e++){const t=o[e],n=a.get(s[e]);void 0!==n&&n!==t?(l[e]=n,c.push({position:e,oldRow:n,newRow:t})):l[e]=t}return c.length>0?{list:l,matched:c}:null}(t.pathInfo.path,i,r,n);if(null!==a)return function(e,t,n,o,s,r){const i=t.pathInfo.path,a=t.listIndex;null===js(o)&&_r(a,null,o);const d=_r(a,o,n.list),u=Kl(e,t,n.list,s,r,i),f=oe(i+l+c);for(const t of n.matched){const n=_l(t.oldRow,t.newRow);if(0===n.length)continue;const o=d.newIndexes[t.position];for(const i of n)void 0!==o?Gl(e,mn(oe(f.path+l+i.field),o),i.value,s,r):t.oldRow[i.field]=i.value}return u}(e,t,a,r,o,s)}}return Kl(e,t,n,o,s,null)}function Kl(e,t,n,s,r,i){const a=r.stateElement,l=t.pathInfo.path,d=a.addressHooks;if(d){const e=d.write;for(let o=0;o<e.length;o++){const i=e[o](a,t,n,s,r);if(i!==ol)return i}}const u=!!lo&&(lo=!1,!0);if(!(l in e)&&null!==t.parentAddress&&!a.elementPaths.has(l)){const f=xl(e,t.parentAddress,s,r);if("object"==typeof f&&null!==f){const e=t.pathInfo.lastSegment,h=e===c?t.listIndex?.index:e;let p,m=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const e=void 0!==h&&h in f,t=void 0!==h?f[h]:void 0;if(e&&Object.is(t,n))return!0;p=t,m=!0}Fl(a,l,m,p,n,()=>f[h]);const g=wl(a,t),y=Ht(a,t);null!==yt&&yt({type:"state:write",absoluteAddress:y,value:n,oldValue:p,hasOldValue:m}),Dl(a,l,y,p,m);let w=!1;try{if(void 0===h&&ee(Fi(`path "${l}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),d&&0!==d.writeMissing.length&&e!==c&&!(h in f)){const e=d.writeMissing;for(let o=0;o<e.length;o++){w=!0;const i=e[o](a,t,f,h,n,s,r);if(i!==ol)return i;w=!1}}return Reflect.set(f,h,n)}finally{ql(t,y,s,r,i,g),w?zs(y):Vl(a,l,y,n,g),Bl(a,t.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=xl(e,t,s,r);if(Al(e,t,s,r)&&Object.is(o,n))return!0;f=o,h=!0}Fl(a,l,h,f,n,()=>xl(e,t,s,r));const p=a.elementPaths.has(t.pathInfo.path),m=wl(a,t),g=Ht(a,t);null!==yt&&yt({type:"state:write",absoluteAddress:g,value:n,oldValue:f,hasOldValue:h}),Dl(a,l,g,f,h);try{return p?Ul(e,t,g,n,s,r,i,m):Hl(e,t,g,n,s,r,i,m)}finally{p||Vl(a,l,g,n,m),Bl(a,t.pathInfo,{value:n})}}function Jl(e,t,n,o){return(t,s,...r)=>{const i=oe(t);if(o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}s.length!==i.wildcardParentPathInfos.length&&ee(Di("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=mn(i,Pl(e,n,o,i,s));if(0===r.length)return xl(e,a,n,o);fl(o),Gl(e,a,r[0],n,o)}}function Xl(e,t,n,o){const s=Jl(e,0,n,o);return(t,r)=>{const i=oe(t);if(void 0===r||Array.isArray(r)||ee(`$getAll("${t}") requires the indexes to be an array when given (omit them for the loop context, or pass [] to expand every level) — got `+(null===r?"null":typeof r)+"."),o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&ee(Di("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=gl(o,i.wildcardPaths[e]);if(t){r=Zt(t,t.length);break}}if(void 0===r){const e=o.addressStackLength>0?o.lastAddressStack:null,n=e?.listIndex??null;i.wildcardCount>0&&null!==e&&null!==n&&n.length>0&&ee(function(e,t){return`$getAll("${e}") was called without indexes inside the loop context of "${t}", but the path shares no wildcard level with that context, so the context indexes ($1..$n) do not apply. Pass indexes explicitly ([] expands every level).`}(t,e.pathInfo.path)),r=[]}}const a=Sl(e,n,o,i,r,{commitDiffBaseline:!0}),l=[];for(let e=0;e<a.length;e++)l.push(s(i.path,a[e]));return l}}function Ql(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return gl(o,s.wildcardPaths.at(-1)??ee(`lastWildcardPath is null: ${t.pathInfo.path}`))??ee(`ListIndex not found: ${t.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<t.pathInfo.wildcardCount;r++){const i=t.pathInfo.wildcardParentPathInfos[r]??ee(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=Ls(xl(e,mn(i,s),n,o),s)??ee(`ListIndex not found: ${i.path}`),l=t.wildcardIndexes[r]??ee(`wildcardIndex is null: ${t.pathInfo.path}`);s=a[l]??ee(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":ee(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function Yl(e,t,n,o){return(t,s,r,i)=>{fl(o);const a=oe(t);Array.isArray(s)||ee(zi(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&ee(Di("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&ee(zi(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&ee(zi(t,"requires an array as the value when { spread: true } is set."));const d=Sl(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&ee(function(e,t,n){return`$setAll("${e}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${t}) but got ${n}. Did the list change between $getAll and $setAll?`}(t,d.length,r.length));const u=[];for(let t=0;t<d.length;t++){const s=Pl(e,n,o,a,d[t]);u.push(mn(a,s))}let f=0;for(let t=0;t<u.length;t++){const s=u[t];let i;if(c){i=r(xl(e,s,n,o),...d[t])}else i=l?r[t]:r;void 0!==i&&(Gl(e,s,i,n,o),f++)}return f}}function Zl(e,t){const n=e.getterPaths;if(0===n.size)return!1;for(const e of oe(t).cumulativePaths)if(n.has(e))return!0;return!1}const ec=/^\$\d+$/,tc=`${G}${l}`,nc=`${K}${l}`,oc=new WeakMap;function sc(e,t,n,o){const s=A[t];if(void 0===s&&"string"==typeof t&&36===t.charCodeAt(0)&&ec.test(t)&&ee(`[wcs/index-param-range] "${t}" is not a valid list index parameter: they run from $1 to $128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&ee(`No active state reference to get list index for "${t.toString()}".`);const e=o.lastAddressStack,n=e?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const r=e?.listIndex;null==r&&ee(`ListIndex not found: ${t.toString()}`);let i=s;const a=e.pathInfo,l=o.stateElement?.addressHooks;if(l){const t=l.indexShift;for(let n=0;n<t.length;n++)i+=t[n](o,e)}const c=Yt(r,i,a.wildcardCount);return c?.index??ee(`ListIndex not found: ${t.toString()}`)}if("string"==typeof t){const s=o.stateElement?.addressHooks;if(s){const r=s.get;for(let s=0;s<r.length;s++){const i=r[s](o,t,n,e);if(i!==ol)return i}}if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>Xl(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>Yl(e,0,n,o)(t,s,r,i);case"$postUpdate":return t=>function(e,t,n,o){const s=o.stateElement;return t=>{const r=ml(t),i=Ql(e,r,n,o),a=mn(r.pathInfo,i),l=Ht(s,a),c=Ys();c.enqueueAbsoluteAddress(l),Wl(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=Ht(s,e);zs(t),c.enqueueAbsoluteAddress(t)});const d=s.addressHooks;if(d){const e=d.written;for(let t=0;t<e.length;t++)e[t](s,a.pathInfo)}}}(e,0,n,o)(t);case"$resolve":return(t,s,...r)=>Jl(e,0,n,o)(t,s,...r);case"$trackDependency":return e=>function(e,t,n,o){return e=>{-1!==e.indexOf(H)&&ee(`[wcs/recursion-unsupported] $trackDependency("${e}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===o.addressStackLength&&ee(`No active state reference to track dependency for path "${e}".`);const t=o.lastAddressStack?.pathInfo??ee("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"$eq":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(Zl(o.stateElement,e))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&gr(o.stateElement,e),Object.is(n[e],t);let r;o.beginUntrack();try{r=n[e]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&mr(o.stateElement,e,t,Ht(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=Zl(o.stateElement,e);let i,a=r?n[e]:void 0;o.beginUntrack();try{r||(a=n[e]),i=n[t]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&(r?gr(o.stateElement,e):mr(o.stateElement,e,i,Ht(o.stateElement,s),a)),Object.is(a,i)};case"$eqIndex":return(e,t=1)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;null!==s&&null!==s.listIndex||ee(`$eqIndex("${e}") needs a list row scope.`);const r=Yt(s.listIndex,t-1,s.pathInfo.wildcardCount);if(null===r&&ee(`$eqIndex("${e}", ${t}): no list index at that level.`),Zl(o.stateElement,e))return o.stateElement.getterPaths.has(s.pathInfo.path)&&gr(o.stateElement,e),Object.is(n[e],r.index);const i=t===s.pathInfo.wildcardCount;let a,l;o.beginUntrack();try{a=n[e],i&&(l=n[s.pathInfo.wildcardParentPaths[t-1]])}finally{o.endUntrack()}if(o.stateElement.getterPaths.has(s.pathInfo.path)){const t=i?js(l):null;null!==t?function(e,t,n,o,s){or=!0,cr(e).lastValue.set(t,s),lr(e,t);let r=sr.get(e);void 0===r&&sr.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=rr.get(o);void 0===l?rr.set(o,l=[]):a=l.find(n=>n.stateElement===e&&n.path===t),void 0===a&&(a={stateElement:e,path:t,indexes:o,getters:new Set},l.push(a),i.add(a)),a.getters.add(n)}(o.stateElement,e,s.pathInfo,t,a):function(e,t,n,o,s){or=!0;const r=cr(e);lr(e,t),pr(r,t,s,o,fr(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,Ht(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untrackDependency":return e=>function(e,t,n,o){return e=>{o.beginUntrack();try{return e()}finally{o.endUntrack()}}}(0,0,0,o)(e);case W:return nl(o.stateElement)}if(!t.startsWith(tc)&&!t.startsWith(nc))return}const r=ml(t),i=Ql(e,r,n,o),a=mn(r.pathInfo,i);return xl(e,a,n,o)}if("symbol"==typeof t){const s=function(e){let t=oc.get(e);return void 0===t&&(t=new Map,oc.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case Ct:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&ee("already in loop context"),e.setLoopContext(t);try{e.pushAddress(t);try{return n()}finally{e.popAddress()}}finally{e.clearLoopContext()}}(o,e,t);break;case Et:i=t=>xl(e,t,n,o);break;case Mt:i=t=>Al(e,t,n,o);break;case Ot:i=(t,s)=>Gl(e,t,s,n,o);break;case Tt:i=()=>async function(e,t,n){const o=Reflect.get(e,C);"function"==typeof o&&await o.call(n)}(e,0,n);break;case Rt:i=()=>function(e,t,n){const o=Reflect.get(e,E);"function"==typeof o&&o.call(n)}(e,0,n);break;case jt:i=t=>function(e,t,n,o){const s=Reflect.get(e,M);let r;if("function"==typeof s){const e=new Set,i={};for(const n of t){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const t=n.absolutePathInfo.pathInfo,s=t.path;if(-1===s.indexOf("#")&&(e.add(s),t.wildcardCount>0)){const e=Zt(n.listIndex,t.wildcardCount),o=i[s];void 0===o?i[s]=[e]:o.push(e)}}r=s.call(n,Array.from(e),i)}const i=o.stateElement?.addressHooks;if(i){const e=i.updated;for(let s=0;s<e.length;s++)e[s](o.stateElement,t,n)}return r}(e,t,n,o);break;case Lt:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,O);"function"==typeof s&&s.call(o,t,n)}(e,t,o,n);break;default:return Reflect.get(e,t,n)}return s.set(t,i),i}}class rc{_stateElement;_addressStack=Array(u).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=ga(e);null===n&&ee("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=t}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let e;return this._addressStackIndex>=0&&(e=this._addressStack[this._addressStackIndex]),void 0===e&&ee("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex+1>=u&&(this._hasRepeatedAddress()&&ee(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),ee(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of 128 with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=e}_hasRepeatedAddress(){const e=new Set;for(let t=0;t<=this._addressStackIndex;t++){const n=this._addressStack[t];if(n){if(e.has(n))return!0;e.add(n)}}return!1}_tailAddressPaths(){const e=[];for(let t=this._addressStackIndex;t>=0&&e.length<8;t--){const n=this._addressStack[t];n&&e.push(n.pathInfo.path)}return e}_describeAddressCycle(){const e=this._tailAddressPaths();return`${Array.from(new Set(e)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const e=this._addressStack[this._addressStackIndex];return void 0===e&&ee(`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 untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(e,t,n){return sc(e,t,n,this)}set(e,t,n,o){return fl(this),function(e,t,n,o,s){if("string"==typeof t){const r=ml(t),i=Ql(e,r,o,s);return Gl(e,mn(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 ic=Promise.resolve(),ac=new Map;let lc=[];function cc(e,t){ac.set(e,t),lc=Array.from(ac.values()).sort((e,t)=>e.order-t.order)}function dc(e,t){return ee(ca(e,t))}const uc="undefined"==typeof HTMLElement?class{}:HTMLElement;function fc(e){const t=[];let n=e;for(;n&&n!==Object.prototype;)t.push(n),n=Object.getPrototypeOf(n);const o={};for(let e=t.length-1;e>=0;e--)Object.assign(o,Object.getOwnPropertyDescriptors(t[e]));return o}let hc=null;const pc=new Set(["for","if","elseif","else"]);function mc(e,n,o){const s=new Map;for(const e of o){const t=oe(e);if(null===t.lastWildcardPath)continue;const n=s.get(t.lastWildcardPath);void 0===n?s.set(t.lastWildcardPath,[t]):n.push(t)}const r=[],i=new Set,a=t=>{const n=Ht(e,t);if(i.has(n))return;i.add(n);const o=un(n);if(o instanceof Set?r.push(...o):void 0!==o&&r.push(o),null!==t.listIndex){const e=s.get(t.pathInfo.path);if(void 0!==e)for(const n of e)a(mn(n,t.listIndex))}};kt();try{if(e.createState("readonly",t=>{for(const o of n){const n=mn(oe(o),null);a(n);try{Wl(e,n,e.staticDependency,e.dynamicDependency,e.listPaths,t,"new",a)}catch{}}}),0===r.length)return;const o=function(e){const t=[],n=[];for(const o of e)pc.has(o.bindingType)?t.push(o):n.push(o);return t.sort((e,t)=>0!==(e.replaceNode.compareDocumentPosition(t.replaceNode)&Node.DOCUMENT_POSITION_FOLLOWING)?-1:1),t.concat(n)}(r),s=()=>{oa(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=Vs("state",s);void 0!==i&&i.catch(Js)}finally{_t()}}class gc extends uc{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return ya(e)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializeFailed=!1;_initializationLanded=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_recursionRegistry=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new Ya}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_stateGeneration=0;_pathRegistrations=new Map;_pendingReapplyPaths=null;_generatedPaths=new Set;_watchPaths=null;_scanPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_addressHooks=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_treeless=!1;_connectGeneration=0;constructor(){super(),this._initializePromise=new Promise(e=>{this._resolveInitialize=e}),this._connectedCallbackPromise=new Promise((e,t)=>{this._resolveConnectedCallback=e,this._rejectConnectedCallback=t}),this._loadingPromise=new Promise(e=>{this._resolveLoading=e}),this._setStatePromise=new Promise(e=>{this._resolveSetState=e})}get _state(){return void 0===this.__state&&ee(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){const t=this.__state,n=function(){const e=new Map;return{get:t=>e.get(t),set(t,n){e.set(t,n)}}}();n.set("previousState",t),function(e,t,n){for(let o=0;o<ll.length;o++)ll[o].validateEarly?.(e,t,n)}(this,e,n);const o=function(e){const t=new Set,n=e[L];if(void 0===n)return t;Array.isArray(n)||ee(`${L} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||ee(`${L} entries must be non-empty strings.`),e===W&&ee(`${L} entry "${e}" conflicts with the reserved namespace name "${W}".`),t.has(e)&&ee(`${L} entry "${e}" is duplicated.`),t.add(e);return t}(e),s=function(e){const t=new Set,n=e[D];if(void 0===n)return t;Array.isArray(n)||ee(`${D} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||ee(`${D} entries must be non-empty strings.`),t.has(e)&&ee(`${D} entry "${e}" is duplicated.`),t.add(e);return t}(e),r=function(e){const t=e[U];if(void 0===t)return null;"object"==typeof t&&null!==t||ee(`${U} must be an object mapping list paths to key specs.`);const n=new Map;for(const[e,o]of Object.entries(t)){0===e.length&&ee(`${U} entry path must be a non-empty string.`);const t=e.split(l);t.some(e=>0===e.length)&&ee(`${U} entry "${e}" must not contain empty path segments.`),t[t.length-1]===c&&ee(`${U} entry "${e}" must be the list path itself, not the element path (drop the trailing "${l}${c}").`),-1!==e.indexOf(H)&&ee(`[wcs/recursion-unsupported] ${U} entry "${e}" uses "${H}", which ${U} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${l}${c}${l}children").`),"function"!=typeof o?("string"!=typeof o&&ee(`${U} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&ee(`${U} entry "${e}" key field name must be a non-empty string.`),(o.includes(l)||o.includes(c))&&ee(`${U} entry "${e}" key field name "${o}" must be a flat property name ("${l}" / "${c}" are not allowed).`),o in Object.prototype&&ee(`${U} entry "${e}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(e,o)):n.set(e,o)}return n.size>0?n:null}(e);var i;n.set("eventTokenNames",s),function(e,t,n){for(let o=0;o<ll.length;o++)ll[o].validate?.(e,t,n)}(this,e,n),function(e,t,n){for(let o=0;o<ll.length;o++)ll[o].preCommit?.(e,t,n)}(this,e,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=e,void 0!==t&&hc?.reset(this),this._hasUpdatedCallback=M in e,this._hasErrorCallback=O in e,i=this,An.delete(i),function(e,t,n){for(let o=0;o<ll.length;o++)ll[o].applyEarly?.(e,t,n)}(this,e,n),function(e,t,n){const o=t[B];if(void 0!==o){"object"==typeof o&&null!==o||ee(`${B} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||ee(`${B} entry "${t}" is not declared in $eventTokens.${ie(t,n)}`),"function"!=typeof s&&ee(`${B} entry "${t}" must be a function.`),Cn(e,t).subscribe(s)}}(this,e,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const a=function(e){const t=new Set,n=new Set,o=fc(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}}(e);for(const e of a.getterPaths)this._getterPaths.add(e);for(const e of a.setterPaths)this._setterPaths.add(e);!function(e,t,n){for(let o=0;o<ll.length;o++)ll[o].apply?.(e,t,n)}(this,e,n),this._listKeys=r,this._rebuildPathInfo(),function(e,t,n){for(let o=0;o<ll.length;o++)ll[o].register?.(e,t,n)}(this,e,n),ul(this,null),this._resolveLoading?.()}attributeChangedCallback(e,t,n){this._initialized&&t!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===t?"absent":`"${t}"`}, now ${null===n?"absent":`"${n}"`}). Remove this <${o.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?ua('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){try{if(this.hasAttribute("state")){return function(e){const t=document.getElementById(e);if(t&&"application/json"===t.type)try{return JSON.parse(t.textContent||"{}")}catch(e){ee("Failed to parse JSON from script element:"+e)}return{}}(this.getAttribute("state"))}if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const e=this.getAttribute("json");return JSON.parse(e)}{const e=this.querySelector('script[type="module"]');if(e)return await Xa(e,o.tagNames.state);{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element.`)},6e4),t=await this._setStatePromise;return clearTimeout(e),t}}}{const e=this.getAttribute("src");if(e&&e.endsWith(".json"))return await async function(e){try{const t=await fetch(e);return t.ok||ee(`Failed to fetch JSON file: ${t.statusText}`),await t.json()}catch(e){return console.error("Failed to load JSON file:",e),{}}}(e);if(e&&e.endsWith(".js"))return await Qa(e);ee(`Unsupported src file type: ${e}`)}}catch(e){ee(`Failed to initialize state: ${e}`)}}async _initialize(){const e=t()?null:this._loadFromSsrElement();if(null!==e&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),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}return await this._loadingPromise,null!==this._rootNode&&(va(this._rootNode,this),!0)}_failInitialization(e){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),ee(e)}_failInitializeLoudly(e,t=!0){if(this._initializationLanded)throw e;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${o.tagNames.state}> failed to initialize.`,e),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(e),t&&null!==this._rootNode&&null===ga(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),ha.set(e,n)}(this._rootNode,e),function(e,t,n){for(let o=0;o<lc.length;o++)lc[o].initializeFailed?.(e,t,n)}(this,this._rootNode,e)),e}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{C in e&&await e[Tt]()})}_callStateDisconnectedCallback(){this.createState("writable",e=>{E in e&&e[Rt]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(e){for(let t=0;t<lc.length;t++)if(!0===lc[t].reconnecting?.(e))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||ga(this._rootNode)===this||va(this._rootNode,this)}else{this.hasAttribute("name")&&this._failInitialization(this.hasAttribute("mount")?'"mount" replaces "name" — a volume has no name of its own. Remove the name attribute.':`The "name" attribute was removed in v2 — there is a single state tree per root. Mount this state onto the tree instead: <wcs-state mount="${this.getAttribute("name")}" ...> and read it as "${this.getAttribute("name")}.<path>".`);const e=function(e){for(let t=0;t<lc.length;t++){const n=lc[t].connecting?.(e);if(null!=n)return n}return null}(this);if(null!==e)return void await e;const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(J))try{dc("dcc",`a <${o.tagNames.state}> inside a [${J}] host`)}catch(e){this._failInitializeLoudly(e)}if(this.hasAttribute("mount"))try{dc("scopes",'the "mount" attribute')}catch(e){this._failInitializeLoudly(e,!1)}let n=!1;try{const e=function(e){for(let t=0;t<lc.length;t++){const n=lc[t].preparing?.(e);if(null!=n)return n}return null}(this);null===e&&this.hasAttribute("bind-component")&&dc("scopes",'the "bind-component" attribute'),n=await(e??!1)}catch(e){this._failInitializeLoudly(e)}if(n)return;let s=!1;try{s=await this._initialize()}catch(e){this._failInitializeLoudly(e)}if(!s)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const e=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(e)}if(this.hasAttribute("enable-ssr")&&!t()||e!==this._connectGeneration||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr")&&!function(){const e=document.documentElement;return!!e&&"orchestrated"===e.getAttribute("data-wcs-server")}())try{await ua('the "enable-ssr" attribute').emitSnapshot(this)}catch(e){throw this._rejectConnectedCallback?.(e),e}ul(this,e),this._resolveConnectedCallback?.()}disconnectedCallback(){var e;if(!function(e){for(let t=0;t<lc.length;t++)if(!0===lc[t].disconnecting?.(e))return!0;return!1}(this)&&null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&function(e,t){for(let n=0;n<lc.length;n++)lc[n].initializeFailureCleared?.(e,t)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{va(this.rootNode,null),e=this,tl.delete(e),function(e){for(let t=0;t<cl.length;t++)cl[t].deactivate?.(e)}(this),this._rootNode=null}}}get initialized(){return this._initialized}get connectedRootNode(){return this._rootNode}clearConnectedRootNode(){this._rootNode=null}markInitialized(){this._initialized=!0}settleInitialization(){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}loadStateFromSource(){return this._loadStateFromSource()}markTreeless(){this._treeless=!0}failInitializeLoudly(e){return this._failInitializeLoudly(e)}get connectGeneration(){return this._connectGeneration}setWatchPaths(e){this._watchPaths=e}setScanPaths(e){this._scanPaths=e}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(e){this._recursionRegistry=e}addGeneratedPath(e){this._generatedPaths.add(e)}setBoundComponent(e,t){this._boundComponent=e,this._boundComponentStateProp=t}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get hasRecursion(){return null!==this._recursionRegistry}get recursionRegistry(){return this._recursionRegistry}get watchPaths(){return this._watchPaths}get scanPaths(){return this._scanPaths}get elementPaths(){return this._elementPaths}addVolumeWatchPaths(e){if(0===e.size)return;const t=new Set(this._watchPaths??[]);for(const n of e)t.add(n);this._watchPaths=t,this.attachAddressHooks("watch",F)}mergeVolumeListKeys(e){if(0===e.size)return;const t=new Map(this._listKeys??[]);for(const[n,o]of e)t.has(n)&&ee(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),t.set(n,o);this._listKeys=t}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(e){this._listPaths.add(e)}findStateDescriptor(e){return Ri(this._state,e)}defineTreeAccessor(e,t){Object.defineProperty(this._state,e,t),"function"==typeof t.get&&this._getterPaths.add(e),"function"==typeof t.set&&this._setterPaths.add(e),this.setPathInfo(e,"prop","internal")}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&ee("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0,this._attachScopeHooks("bind-component")}get hasGraftedVolumes(){return this._hasGraftedVolumes}get addressHooks(){return this._addressHooks}attachAddressHooks(e,t){const n=function(e,t){const n=rl.get(e);return void 0===n&&ee(ca(e,`"${t}"`)),n}(e,t);null===this._addressHooks&&(this._addressHooks={read:[],readMissing:[],write:[],writeMissing:[],writeObserve:[],written:[],swapped:[],get:[],indexShift:[],handlerScope:[],updated:[],suppressPathDiagnostic:[],rowReused:[]}),function(e,t){for(let n=0;n<sl.length;n++){const o=sl[n],s=t[o];if(void 0===s)continue;const r=e[o];r.includes(s)||r.push(s)}}(this._addressHooks,n)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(e){this.attachAddressHooks("scopes",e)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(e){this._bindableEventMap=e,this.attachAddressHooks("dcc",R)}_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,n="binding"){if("internal"!==n){const o=this._pathRegistrations.get(e);void 0===o?this._pathRegistrations.set(e,{bindingType:t,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(e,{bindingType:t,bound:o.bound||"binding"===n})}if("for"===t&&(this._listPaths.add(e),this._elementPaths.add(e+"."+c)),!this._pathSet.has(e)){const t=oe(e);if(this._pathSet.add(e),hc?.check(this,this.__state,e,n),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=oe(e.parentPath)}}}_rebuildPathInfo(){for(const[e,t]of Array.from(this._pathRegistrations))t.bound&&!this._generatedPaths.has(e)&&this.setPathInfo(e,t.bindingType)}_createState(e,t,n){try{const o=function(e,t,n){const o=new rc(e,n);return new Proxy(t,o)}(e,this._state,t);return n(o)}finally{}}async createStateAsync(e,t){return await this._createState(this.rootNode,e,t)}createState(e,t){this._createState(this.rootNode,e,t)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(e){this._crossRowListPaths.add(e)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(e){this._indexDependentGetterPaths.add(e)}setInitialState(e){if(!this._initialized)return this._initializeFailed&&ee(`<${o.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(e);!function(e){for(let t=0;t<lc.length;t++)lc[t].replacingState?.(e)}(this),(this._hasGraftedVolumes||this._hasMounts)&&ee("Cannot replace the whole state of a tree that has grafted volumes or mounted components: re-setting would silently drop grafted data, tree accessors and mount ledgers (D22). Write the changed paths instead.");const t=this.__state;this._state=e;const n=function(e){const t=new Set;for(const n of e)if(void 0!==n)for(const[e,o]of Object.entries(fc(n)))e.startsWith("$")||e.includes(c)||"function"==typeof o.value||t.add(e);return t}([t,e]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(e){mc(this,e,this._pathRegistrations.keys())}}const yc=[];function wc(e=customElements){for(let t=0;t<yc.length;t++)yc[t](e);e.get(o.tagNames.state)||e.define(o.tagNames.state,gc)}function bc(e){const t=function(){const e=document.documentElement?.lang;if(e)try{return Intl.getCanonicalLocales(e),e}catch{return void console.warn(`[@wcstack/state] <html lang="${e}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===t?e:{...e,locale:t}}function vc(e,t){const o=bc(e);var r;o&&((r=o).tagNames&&Object.assign(n.tagNames,r.tagNames),"string"==typeof r.bindAttributeName&&(n.bindAttributeName=r.bindAttributeName),"string"==typeof r.commentTextPrefix&&(n.commentTextPrefix=r.commentTextPrefix),"string"==typeof r.commentForPrefix&&(n.commentForPrefix=r.commentForPrefix),"string"==typeof r.commentIfPrefix&&(n.commentIfPrefix=r.commentIfPrefix),"string"==typeof r.commentElseIfPrefix&&(n.commentElseIfPrefix=r.commentElseIfPrefix),"string"==typeof r.commentElsePrefix&&(n.commentElsePrefix=r.commentElsePrefix),"string"==typeof r.locale&&(n.locale=r.locale),"boolean"==typeof r.debug&&(n.debug=r.debug),"boolean"==typeof r.enableMustache&&(n.enableMustache=r.enableMustache),"boolean"==typeof r.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=r.enableDirectionalInitialSync),"boolean"==typeof r.enablePropagationContext&&(n.enablePropagationContext=r.enablePropagationContext),"boolean"==typeof r.enableContractAnalyzer&&(n.enableContractAnalyzer=r.enableContractAnalyzer),"boolean"==typeof r.sameValueGuard&&(n.sameValueGuard=r.sameValueGuard)),wc(t),function(){const e=globalThis;void 0===e[s]&&(e[s]=Ga)}()}function $c(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function xc(e,t){for(const n of e)if($c(t,n.innerSegments))return n;return null}function Sc(e,t){const n=t.slice(e.innerSegments.length);return 0===n.length?e.outerPathInfo.path:e.outerPathInfo.path+l+n.join(l)}let Pc=0;const Ic=["$watch","$streams","$scan","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],Nc=new Set;function kc(e,t){const n=e.stateObject[t];if("function"==typeof n)try{const o=e.component[e.stateProp],s=n.call(o);s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)}}function _c(e,t,n,o,s,r=new Set){0===n.length&&ee(`Cannot build a mount record without host bindings for "${t}".`);const i=[],a=new Set;let c=null;for(const e of n){const t=e.propSegments.slice(1),n=t.join(l);a.has(n)&&ee("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo,readonly:!0===e.propModifiers?.includes(g)};i.push(o),0===t.length&&(c=o)}i.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const d=++Pc,u=`#m${d}`,{getterKeys:f,setterKeys:h}=function(e){const t=new Set,n=new Set,o=Object.getOwnPropertyDescriptors(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterKeys:t,setterKeys:n}}(s),p=new Set;for(const e of i)e.innerSegments.length>0&&p.add(e.innerSegments[0]);const m={};for(const e of Object.keys(s))e.startsWith("$")||f.has(e)||h.has(e)||"function"!=typeof s[e]&&(r.has(e)||p.has(e)||(m[e]=s[e]));return{id:d,marker:u,component:e,stateProp:t,parentStateElement:o,entries:i,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?u:c.outerPathInfo.path+l+u,stateObject:s,getterKeys:f,setterKeys:h,injectedKeys:r,mappedKeys:p,privateSnapshot:m,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function Ac(e){const t=e.indexOf(l);return-1===t?e:e.slice(0,t)}function Cc(e,t){const n=xc(e.entries,t);return null===n?null:Sc(n,t)}function Ec(e,t){return e.markerBasePath+l+t}function Mc(e,t,n,o){let s=e.accessorBySuffixByMarkerParent.get(t);void 0===s&&(s=new Map,e.accessorBySuffixByMarkerParent.set(t,s));const r=t+l+n;s.set(n,{accessorName:o,indexShift:oe(r).wildcardCount-oe(o).wildcardCount}),e.getterKeys.has(o)&&(e.parentStateElement.getterPaths?.add(r),e.addedGetterPaths.add(r))}function Oc(e,t){return!e.injectedKeys.has(t)&&!e.mappedKeys.has(t)&&("function"==typeof e.stateObject[t]&&!e.getterKeys.has(t)||Object.prototype.hasOwnProperty.call(e.stateObject,t)&&!e.getterKeys.has(t)&&!e.setterKeys.has(t))}function Tc(e,t){return`Path "${t}" in <${e.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${e.entries.filter(e=>e.innerSegments.length>0).map(e=>e.innerSegments.join(l)).join(", ")}). Mount it from the host ("${e.stateProp}: path" / "${e.stateProp}.${Ac(t)}: path") or declare the key on the component state.`}const Rc=/^\$(\d+)$/;function jc(e,t){const n=t[0];if("$"===n||"#"===n)return null;if(e.getterKeys.has(t)||e.setterKeys.has(t))return null;const o=Ac(t);if(e.getterKeys.has(o)||e.setterKeys.has(o)||Oc(e,o))return null;const s=function(e,t){return xc(e.entries,t)}(e,t.split(l));return null!==s&&s.readonly?s:null}function Lc(e,t){const n=jc(e,t);if(null!==n){const o=0===n.innerSegments.length?"":l+n.innerSegments.join(l);ee(`[wcs/mount-readonly] <${e.component.tagName.toLowerCase()}> cannot write "${t}": it is mounted read-only ("${e.stateProp}${o}#${g}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${g} from the mount.`)}return Wc(e,t)}function Wc(e,t){const n=t[0];if("$"===n||"#"===n)return t;if(e.getterKeys.has(t)||e.setterKeys.has(t))return function(e,t){const n=t.split(l);let o=-1;for(let e=n.length-1;e>=0;e--)if(n[e]===c){o=e;break}if(-1===o)return Mc(e,e.markerBasePath,t,t),Ec(e,t);if(Oc(e,n[0]))return Mc(e,e.markerBasePath,t,t),Ec(e,t);const s=n.slice(0,o+1),r=n.slice(o+1),i=Cc(e,s);null===i&&ee(Tc(e,t)),0===r.length&&ee(`Wildcard-terminal accessor "${t}" on mounted <${e.component.tagName.toLowerCase()}> is not supported: it translates to a marker-terminal path where the mount overlay would shadow the accessor. Declare the row value as a getter on the host tree, or back it with a component-own array (a private key makes the whole path private).`);const a=i+l+e.marker;return Mc(e,a,r.join(l),t),a+l+r.join(l)}(e,t);const o=Ac(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return Ec(e,t);if(Oc(e,o))return Ec(e,t);const s=Cc(e,t.split(l));if(null!==s)return s;ee(Tc(e,t))}function Dc(e,t,n){let o;const s=Rc.exec(t.statePathName);if(null!==s){const r=function(e,t){return void 0===t?e.delta:oe(Wc(e,t)).wildcardCount-oe(t).wildcardCount}(e,n);o=0===r?t.statePathName:`$${Number(s[1])+r}`}else if(o=Wc(e,t.statePathName),"for"===t.bindingType){const n=oe(o).wildcardCount-t.statePathInfo.wildcardCount;e.indexShiftByLoopElementPath.set(o+l+c,n)}const r=t.propModifiers,i=null===s&&Array.isArray(r)&&!r.includes(g)&&null!==jc(e,t.statePathName);return o!==t.statePathName||i?{...t,statePathName:o,statePathInfo:oe(o),...i?{propModifiers:[...r,g]}:{}}:t}function Bc(e,t,n,o,s){if(void 0===o)return;const r=oe(n).wildcardCount-oe(t).wildcardCount;return 0===r?o:(s.length<r&&ee(`Cannot resolve "${t}" from this mount: the mounted prefix has ${r} wildcard(s) but the host context provides only ${s.length} index(es).`),[...s.slice(0,r),...o])}const zc=new WeakMap,Fc=new WeakMap;const qc=new WeakMap;const Vc=new FinalizationRegistry(function(e){const t=e.byMarker.get(e.marker);if(void 0!==t&&void 0===t.deref()&&e.byMarker.delete(e.marker),void 0!==e.getterPaths)for(const t of e.addedGetterPaths)e.getterPaths.delete(t)}),Hc=new WeakMap;function Uc(e){return Hc.get(e)??null}let Gc=!1;function Kc(){Gc||(Gc=!0,pt=e=>zc.has(e)?e.host:null)}function Jc(e){const t=qc.get(e);if(void 0===t)return[];const n=[];for(const e of t.values()){const t=e.deref();void 0!==t&&n.push(t)}return n}function Xc(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=qc.get(e);if(void 0===o)return null;const s=t.indexOf(l,n),r=-1===s?t.slice(n):t.slice(n,s),i=o.get(r);if(void 0===i)return null;const a=i.deref();return void 0===a?(o.delete(r),null):a}const Qc="3.1.0",Yc=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Zc(e,t,n,o){return{node:e,propName:t.propName,statePathName:t.statePathName,bindingType:t.bindingType,inFilters:t.inFilters,outFilters:t.outFilters,origin:n,raw:o}}function ed(e){const t=function(e){const t=Zs.get(e);return void 0===t?null:{byPath:t.byPath,lastValue:t.lastValue,tracked:t.tracked,watchers:sr.get(e)}}(e);if(null===t)return[];const n=new Set([...t.byPath.keys(),...t.tracked]);if(void 0!==t.watchers)for(const e of t.watchers.keys())n.add(e);const o=[];for(const e of[...n].sort()){const n=t.byPath.get(e);let s=0;if(void 0!==n)for(const e of n.values())s+=e.size;o.push({path:e,tracked:t.tracked.has(e),rows:s,keys:n?.size??0,lists:t.watchers?.get(e)?.size??0,lastValue:t.lastValue.get(e)})}return o}const td="__WCSTACK_DEVTOOLS_HOOK__";function nd(){const e=globalThis,t=e[td];if(void 0!==t)return 2!==t.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${t.version}, expected 2. Keeping the existing registry (first-wins).`),t;const n=function(){const e=new Map,t=new Set,n=e=>{if(0===t.size)return void e._setSink(null);const n=e.id;e._setSink(e=>{for(const o of t)o.onEvent?.(n,e)})};return{version:2,sources:e,register(o){if(!e.has(o.id)){e.set(o.id,o),n(o);for(const e of t)e.onSourceRegistered?.(o)}},unregister(n){const o=e.get(n);if(void 0!==o){o._setSink(null),e.delete(n);for(const e of t)e.onSourceUnregistered?.(n)}},addListener(o){t.add(o);for(const t of e.values())n(t),o.onSourceRegistered?.(t);return()=>{if(t.delete(o))for(const t of e.values())n(t)}}}}();return e[td]=n,n}const od=e=>{null!==yt&&yt({type:"state:update-batch",addresses:e})};function sd(e){const t=null!==yt;!function(e){yt=e}(e);const n=null!==e;n&&!t?Ks(od,0):!n&&t&&function(e){const t=Hs.findIndex(t=>t.listener===e);-1!==t&&Hs.splice(t,1)}(od)}function rd(e){return{rootNode:e.rootNode,element:e,paths:{list:e.listPaths,element:e.elementPaths,getter:e.getterPaths,setter:e.setterPaths},commandTokenNames:e.commandTokenNames,eventTokenNames:e.eventTokenNames,staticDependency:e.staticDependency,dynamicDependency:e.dynamicDependency,watchPaths:e.watchPaths??null,keyedListPaths:void 0===e.listKeys||null===e.listKeys?null:new Set(e.listKeys.keys())}}function id(e){return ga(e)??ee("devtools: no state tree on this root")}let ad=null;function ld(){if(t())return;if(null!==ad)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Qc,getStateElements(){const e=[];for(const t of pa)e.push(rd(t));return e},overlays:e=>Jc(id(e)).map(e=>({marker:e.marker,componentTag:e.component.tagName.toLowerCase(),stateProp:e.stateProp,mountTable:e.entries.map(e=>({inner:e.innerSegments.join("."),outer:e.outerPathInfo.path})),delta:e.delta,privateKeys:Object.keys(e.privateSnapshot),getterKeys:[...e.getterKeys],exports:[...e.exports.keys()]})),keyedSubscriptions:e=>ed(id(e)),keys(e){const t=id(e),n=[];return t.createState("readonly",e=>{for(const t of Object.keys(e))if(!t.includes("*")&&!t.startsWith("$")){try{if("function"==typeof e[t])continue}catch{}n.push(t)}}),n},read(e,t,n){let o;return id(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){id(e).createState("writable",e=>{void 0!==o&&o.length>0?e.$resolve(t,o,n):e[t]=n})},getDeclaredBindings:e=>function(e){const t=[],n=new Set,s=new Set,r=e=>{const o=function(e){const t=[...e.inFilters,...e.outFilters].map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.statePathName,e.propName,e.bindingType,t].join("\0")}(e);n.has(o)||(n.add(o),t.push(e))},i=e=>{if(s.has(e))return;s.add(e);const t=Sa(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(Zc(null,t,"fragment","")),null!=t.uuid&&i(t.uuid)},a=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let e=a.nextNode();null!==e;e=a.nextNode()){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=t.getAttribute(o.bindAttributeName);if(null===n||0===n.length)continue;try{const e=Ze(t,Ce(n));for(const o of e)r(Zc(t,o,"attribute",n))}catch{}continue}const t=Yc.exec(e.data.trim());if(null===t)continue;const n=t[1]||o.commentTextPrefix,s=t[2],a=Sa(s);if(null===a){if(n===o.commentTextPrefix)try{r(Zc(e,Re(s),"comment",s))}catch{}}else r(Zc(e,a.parseBindTextResult,"comment",s)),i(s)}return t}(e),_setSink:sd};ad=e,nd().register(e)}const cd={name:"devtools",install(){ld()}},dd=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),ud=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});const fd=new WeakMap;const hd=new WeakMap,pd=new WeakSet,md=new WeakMap;function gd(e,t,n,o){console.warn(`[@wcstack/state] [${Li[n]}] ${Wi[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${ie(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${ae}`),null!==yt&&yt({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const yd={check:function(e,t,n,o){if("internal"===o||void 0===t)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const s=e.addressHooks;if(s){const t=s.suppressPathDiagnostic;for(let o=0;o<t.length;o++)if(t[o](e,n))return}const r=oe(n).segments;if("binding"===o&&r.length<2)return;if(function(e,t){let n=fd.get(e);return void 0===n&&(n=new Set,fd.set(e,n)),!!n.has(t)||(n.add(t),!1)}(e,n))return;if(!0===e.hasRecursion&&null!==e.recursionRegistry.recursiveGetterOwning(n))return;const i=function(e,t,n){if(void 0!==Ri(e,t))return ud;const o=oe(t).segments;let s=e,r="";for(let t=0;t<o.length;t++){const i=o[t],a=r;if(r=0===t?i:r+l+i,t>0&&t<o.length-1&&void 0!==Ri(e,r))return dd;if(Object(s)!==s)return dd;if(i===c){if(!Array.isArray(s)||0===s.length)return dd;s=s[0];continue}const d=Ri(s,i);if(void 0===d)return{existence:"missing",missingSegment:i,candidates:ji(s,a,n)};if("function"==typeof d.get)return t===o.length-1?ud:dd;s=d.value}return ud}(t,n,e.getterPaths);"missing"===i.existence&&(function(e,t){return!0===md.get(e)?.has(t)}(e,n)||("binding"!==o?gd(e,n,o,i):function(e,t,n){let o=hd.get(e);void 0===o&&(o=new Map,hd.set(e,o));if(o.set(t,n),pd.has(e))return;pd.add(e),setTimeout(()=>function(e){pd.delete(e);const t=hd.get(e);if(void 0===t)return;hd.delete(e);for(const[n,o]of t)gd(e,n,"binding",o)}(e),0)}(e,n,i)))},reset:function(e){fd.delete(e),hd.delete(e)},markExported:function(e,t){let n=md.get(e);void 0===n&&(n=new Set,md.set(e,n)),n.add(t),hd.get(e)?.delete(t)}};let wd=!1;function bd(){wd||(wd=!0,function(e){hc=e}(yd))}const vd={name:"diagnostics",install(){bd()}};function $d(e){ee(`filter ${e} requires at least one option`)}function xd(e){ee(`filter ${e} requires a number as option`)}function Sd(e){ee(`filter ${e} requires a number value`)}function Pd(e){ee(`filter ${e} requires a date value`)}function Id(e){return!(!e||isNaN(Number(e)))}const Nd={eq:(e,t)=>{const n=e?.[0]??$d("eq"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?(Id(n)||xd("eq"),e===Number(n)):"string"==typeof e?e===n:e===o},ne:(e,t)=>{const n=e?.[0]??$d("ne"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?(Id(n)||xd("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==o},not:e=>e=>("boolean"!=typeof e&&ee(`filter ${"not"} requires a boolean value`),!e),lt:e=>{const t=e?.[0]??$d("lt");return Id(t)||xd("lt"),e=>("number"!=typeof e&&Sd("lt"),e<Number(t))},le:e=>{const t=e?.[0]??$d("le");return Id(t)||xd("le"),e=>("number"!=typeof e&&Sd("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??$d("gt");return Id(t)||xd("gt"),e=>("number"!=typeof e&&Sd("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??$d("ge");return Id(t)||xd("ge"),e=>("number"!=typeof e&&Sd("ge"),e>=Number(t))},inc:e=>{const t=e?.[0]??$d("inc");return Id(t)||xd("inc"),e=>("number"!=typeof e&&Sd("inc"),e+Number(t))},dec:e=>{const t=e?.[0]??$d("dec");return Id(t)||xd("dec"),e=>("number"!=typeof e&&Sd("dec"),e-Number(t))},mul:e=>{const t=e?.[0]??$d("mul");return Id(t)||xd("mul"),e=>("number"!=typeof e&&Sd("mul"),e*Number(t))},div:e=>{const t=e?.[0]??$d("div");return Id(t)||xd("div"),e=>("number"!=typeof e&&Sd("div"),e/Number(t))},mod:e=>{const t=e?.[0]??$d("mod");return Id(t)||xd("mod"),e=>("number"!=typeof e&&Sd("mod"),e%Number(t))},abs:e=>e=>("number"!=typeof e&&Sd("abs"),Math.abs(e)),clamp:e=>{const t=e?.[0]??$d("clamp");Id(t)||xd("clamp");const n=e?.[1]??$d("clamp");Id(n)||xd("clamp");const o=Number(t),s=Number(n);return e=>("number"!=typeof e&&Sd("clamp"),Math.min(Math.max(e,o),s))},fix:e=>{const t=e?.[0]??"0";return Id(t)||xd("fix"),e=>("number"!=typeof e&&Sd("fix"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&Sd("locale"),e.toLocaleString(t??o.locale))},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]??$d("slice");Id(n)||xd("slice"),t.push(Number(n));const o=e?.[1];return void 0!==o&&(Id(o)||xd("slice"),t.push(Number(o))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??$d("substr");Id(t)||xd("substr");const n=e?.[1]??$d("substr");return Id(n)||xd("substr"),e=>String(e).substr(Number(t),Number(n))},pad:e=>{const t=e?.[0]??$d("pad");Id(t)||xd("pad");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},rep:e=>{const t=e?.[0]??$d("rep");return Id(t)||xd("rep"),e=>String(e).repeat(Number(t))},rev:e=>e=>String(e).split("").reverse().join(""),truncate:e=>{const t=e?.[0]??$d("truncate");Id(t)||xd("truncate");const n=Number(t),o=e?.[1]??"…";return e=>{const t=String(e);return t.length<=n?t:t.slice(0,n)+o}},join:e=>{const t=e?.[0]??", ";return e=>(Array.isArray(e)||ee(`filter ${"join"} requires an array value`),e.join(t))},int:e=>e=>parseInt(String(e),10),float:e=>e=>parseFloat(String(e)),round:e=>{const t=e?.[0]??"0";return Id(t)||xd("round"),e=>{"number"!=typeof e&&Sd("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return Id(t)||xd("floor"),e=>{"number"!=typeof e&&Sd("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return Id(t)||xd("ceil"),e=>{"number"!=typeof e&&Sd("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return Id(t)||xd("percent"),e=>("number"!=typeof e&&Sd("percent"),`${(100*e).toFixed(Number(t))}%`)},unit:e=>{const t=e?.[0]??$d("unit");return e=>null==e?e:String(e)+t},date:e=>{const t=e?.[0];return e=>(e instanceof Date||Pd("date"),e.toLocaleDateString(t??o.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||Pd("time"),e.toLocaleTimeString(t??o.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||Pd("datetime"),e.toLocaleString(t??o.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||Pd("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}`}},hms:e=>{const t=e?.[0]??":";return e=>{e instanceof Date||Pd("hms");const n=e.getHours().toString().padStart(2,"0"),o=e.getMinutes().toString().padStart(2,"0"),s=e.getSeconds().toString().padStart(2,"0");return`${n}${t}${o}${t}${s}`}},falsy:e=>e=>!e,truthy:e=>e=>!!e,defaults:(e,t)=>{const n=e?.[0]??$d("defaults"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e||o},boolean:e=>e=>Boolean(e),number:e=>e=>Number(e),string:e=>e=>String(e),null:e=>e=>""===e?null:e},kd={eq:[1,1],not:[0,0],ne:[1,1],lt:[1,1],le:[1,1],gt:[1,1],ge:[1,1],inc:[0,1],dec:[0,1],mul:[1,1],div:[1,1],mod:[1,1],abs:[0,0],clamp:[2,2],fix:[0,1],locale:[0,1],uc:[0,0],lc:[0,0],cap:[0,0],trim:[0,0],slice:[1,2],substr:[1,2],pad:[1,2],rep:[1,1],rev:[0,0],truncate:[1,2],join:[0,1],int:[0,0],float:[0,0],round:[0,1],floor:[0,1],ceil:[0,1],percent:[0,1],unit:[1,1],date:[0,0],time:[0,0],datetime:[0,0],ymd:[0,1],hms:[0,1],falsy:[0,0],truthy:[0,0],defaults:[1,1],boolean:[0,0],number:[0,0],string:[0,0],null:[0,0]},_d=Nd,Ad=Nd;let Cd=!1;const Ed={name:"formats",install(){Cd||(Cd=!0,he("input",Ad,kd),he("output",_d,kd))}};function Md(e){return-1!==e.indexOf(H)}function Od(e,t){if(t===e.recursiveAnchor)return"";const n=e.recursiveAnchor+l;if(!t.startsWith(n))return null;const o=t.slice(e.recursiveAnchor.length);if(Md(o))return null;const s=o.slice(1).split(l);return s[0]===c||s.some(e=>0===e.length)?null:o}function Td(e){return 0===e.length?e:l+Ld(e.slice(1))}function Rd(e,t,n){const o=l+e.repeat,s=t.length<=n.length?t:n,r=t.length<=n.length?n:t;if(!r.endsWith(s))return!1;const i=r.slice(0,r.length-s.length);if(0===i.length)return!0;if(i.length%o.length!==0)return!1;for(let e=0;e<i.length;e+=o.length)if(!i.startsWith(o,e))return!1;return!0}function jd(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(l,o-1))if(Rd(e,t,n.slice(0,o)))return!0;return!1}function Ld(e){const t=e.split(l);for(let e=0;e<t.length;e++)t[e]===c||Number.isNaN(Number(t[e]))||(t[e]=c);return t.join(l)}function Wd(e,t){const n=e.repeat.split(l),o=l+e.repeat;let s=t;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===l+e.repeatList+l+"length")return!0;for(let e=1;e<n.length;e++)if(s===l+n.slice(0,e).join(l))return!0;return!1}function Dd(e,t,n){n<0&&ee(`Recursion depth must not be negative (got ${n}).`);let o=e.anchor;for(let t=0;t<n;t++)o+=l+e.repeat;const s=o+t;let r=0;for(const e of s.split(l))e===c&&r++;return r>d&&ee(`[wcs/recursion-depth-exceeded] Recursion on "${e.anchor}" reached depth ${n} ("${s}"), which needs ${r} wildcard levels — the limit is 128. Either the data nests deeper than the engine can address, or the tree contains a cycle.`),s}function Bd(e,t){return Dd(e,"",t)}function zd(e,t,n){if(!n.startsWith(e.anchor))return null;if(t.length>0&&!n.endsWith(t))return null;if(n.length<e.anchor.length+t.length)return null;const o=n.slice(e.anchor.length,n.length-t.length);if(0===o.length)return 0;const s=l+e.repeat;let r=0,i=0;for(;i<o.length;){if(!o.startsWith(s,i))return null;i+=s.length,r++}return r}function Fd(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const o=t.accessorFor(n.pathInfo.path);return null!==o?o.depth:function(e,t){const n=e.spec;if(!t.startsWith(n.anchor))return null;const o=l+n.repeat;let s=0,r=n.anchor.length;for(;t.startsWith(o,r);)r+=o.length,s++;return r!==t.length&&46!==t.charCodeAt(r)?null:s}(t,n.pathInfo.path)}function qd(e,t,n){const o=e.recursionRegistry,s=Od(o.spec,n);null===s&&ee(Bi(n,o.spec.recursiveAnchor));const r=Fd(t,o);return null===r&&ee(`[wcs/recursion-context] "${n}" uses "**", which is bound to the depth of the recursive getter being evaluated, and there is no recursion context here. Read it from inside a recursive getter or a row getter under "${o.spec.anchor}", or name a concrete depth (for example "${o.spec.anchor}${n.slice(o.spec.recursiveAnchor.length)}"). The depth comes from the innermost frame only: a plain getter reached from a recursive getter has no row of its own, so read "**" in the recursive getter and pass the value on.`),o.concretePathAt(s,r)}function Vd(e,t,n,o,s){const r=o.spec,i=[],a=new Map,c=[],d=r.repeatList,u=r.anchorList,f=new Set,h=new Set,p=(e,t,n)=>{const o=e.wildcardParentPathInfos;if(t>=o.length)return void i.push(mn(e,n));const s=m(o[t],n,null).rows;for(let n=0;n<s.length;n++)p(e,t+1,s[n])};function m(o,s,i){const l=mn(o,s),c=Ht(n.stateElement,l),u=xl(e,l,t,n),h=null===i?null:((e,t,n)=>{if(!Array.isArray(t)||0===t.length)return null;const o=t;return f.has(o)&&ee(`[wcs/recursion-cycle] "${e}" is reachable from itself: the recursion on "${r.anchor}" walked into a list that one of its own ancestors already owns. The data contains a cycle, which this version does not support.`),n.has(o)&&ee(`[wcs/recursion-shared-list] "${e}" is the same array instance as a list reached from another node. The recursion on "${r.anchor}" needs a tree: give each node its own "${d}" array.`),o})(o.path,u,i),p=_r(s,It(c),u);return a.set(c,Array.isArray(u)?u:[]),null!==h&&null!==i&&i.add(h),{rows:p.newIndexes,tracked:h}}const g=(e,t,n)=>{const{rows:r,tracked:a}=m(t,n,h);if(0===r.length)return;const u=(e=>{const t=c[e];if(void 0!==t)return t;const n=o.concretePathAt(s,e),r=0===s.length?n:o.concretePathAt("",e),i={nodePath:r,concretePathInfo:oe(n),childListPathInfo:oe(r+l+d)};return c[e]=i,i})(e),y=a;f.add(y);const w=u.concretePathInfo.wildcardCount===e+1;for(let t=0;t<r.length;t++){const n=r[t];w?i.push(mn(u.concretePathInfo,n)):p(u.concretePathInfo,e+1,n),g(e+1,u.childListPathInfo,n)}f.delete(y)};g(0,oe(u),null);for(const[e,t]of a)Nt(e,t);return i}function Hd(e,t,n,o,s,r,i){fl(n);const a=n.stateElement.recursionRegistry,l=Od(a.spec,o);null===l&&ee(Bi(o,a.spec.recursiveAnchor));const c=Td(l);Array.isArray(s)||ee(zi(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&ee(`[wcs/recursion-setall-form] $setAll("${o}", indexes, …) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Pass [] to broadcast to every depth.`),"function"==typeof r&&ee(zi(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&ee(zi(o,'with "**" does not take { spread: true } — handing a flat array to a tree needs the author to know the walk order, which is not a usable contract.')),function(e,t,n){Wd(e,n)&&ee(`[wcs/recursion-structural-write] "${t}" writes the recursion structure itself (a node, its "${e.repeatList}" list or that list's length, or an object on the way to that list). This version broadcasts to leaf properties only — replacing a node would invalidate the child addresses already resolved for this write.`)}(a.spec,o,c);const d=a.conflictingRecursiveGetter(c);null!==d&&ee(`[wcs/recursion-readonly] "${o}" writes into the recursive getter "${d}", which has no setter — the two name the same family of concrete paths (or this path points inside the value that getter derives). Write the values it derives from instead.`);const u=Vd(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(Gl(e,u[o],r,t,n),f++);return f}const Ud={write(e,t){if(!0!==e.hasRecursion)return ol;const n=e.recursionRegistry.recursiveGetterOwningPath(t.pathInfo);return null!==n&&ee(`[wcs/recursion-readonly] "${t.pathInfo.path}" writes into the recursive getter "${n}" (this path is that getter at one depth, or a path inside the value it derives), which has no setter. Write the values it derives from instead.`),ol},get(e,t,n,o){if(!0!==e.stateElement.hasRecursion)return ol;if("$getAll"===t)return(t,s)=>{if(Md(t)){if(void 0!==s)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=Od(r.spec,o);null===i&&ee(Bi(o,r.spec.recursiveAnchor)),Array.isArray(s)||ee(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes either no indexes (to read the depth of the recursive getter being evaluated) or [] (to walk every depth) — got ${null===s?"null":typeof s}.`),s.length>0&&ee(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Omit the indexes to read the depth of the recursive getter being evaluated, or pass [] to walk every depth.`);const a=Vd(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(xl(e,a[o],t,n));return l}(o,n,e,t,s);t=qd(e.stateElement,e,t)}return Xl(o,0,n,e)(t,s)};if("$setAll"===t)return(t,s,r,i)=>Md(t)?Hd(o,n,e,t,s,r,i):Yl(o,0,n,e)(t,s,r,i);if(36!==t.charCodeAt(0)&&Md(t)){const s=ml(qd(e.stateElement,e,t)),r=Ql(o,s,n,e);return xl(o,mn(s.pathInfo,r),n,e)}return ol}};let Gd=!1;function Kd(e,t){"string"==typeof t&&0!==t.length||ee(`[wcs/recursion-declaration-invalid] ${V} ${e} must be a non-empty string.`);const n=t.split(l);n.some(e=>0===e.length)&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must not contain empty path segments.`),n.length<2&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must name a list element: a property path ending with "${l}${c}" (for example "nodes${l}${c}").`),n[n.length-1]!==c&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must end with "${l}${c}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===c&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must have exactly one "${c}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===H&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must not contain "${H}" — the declaration is what gives "${H}" its meaning.`),isNaN(Number(n[o]))||ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}const Jd=new WeakSet;function Xd(e){return"function"==typeof e.get&&Jd.has(e.get)}function Qd(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&Xd(n)&&delete t[e]}for(const t of[e.staticDependency,e.dynamicDependency]){for(const e of n)t.delete(e);for(const[e,o]of t){let s=null;for(let e=0;e<o.length;e++)n.has(o[e])?s??=o.slice(0,e):s?.push(o[e]);null!==s&&(0===s.length?t.delete(e):t.set(e,s))}}!function(e,t,n){for(const o of n){const n=oe(o),s=n.wildcardParentPathInfos,r=(t,o,i)=>{if(i===s.length)return void Bs(Ut(e,n,o),null);const a=0===i?0:s[i-1].segments.length+1;let l=t;for(const e of s[i].segments.slice(a))l=l?.[e];if(!Array.isArray(l))return;const c=js(l);if(null===c)return;const d=Math.min(c.length,l.length);for(let e=0;e<d;e++)r(l[e],c[e],i+1)};r(t,null,0)}}(e,t,n)}}const Yd="[wcs/recursion-declaration-invalid]";class Zd{spec;_definitions=new Map;_accessors=new Map;_ownerByPath=new Map;_ownerByPathInfo=new WeakMap;_accessorByPathInfo=new WeakMap;_concreteBySuffix=new Map;_registeredListPaths=new Set;constructor(e,t){this.spec=e;const n=fc(t);for(const[t,o]of Object.entries(n)){if(!Md(t))continue;"function"==typeof o.set&&ee(`${Yd} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&ee(`${Yd} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Od(e,t);null===n&&ee(Bi(t,e.recursiveAnchor)),0===n.length&&ee(`${Yd} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${l}total"), not the node.`),Wd(e,Td(n))&&ee(`${Yd} "${t}" names the recursion structure itself (a node, its "${e.repeatList}" list or that list's length, or an object on the way to that list). A recursive getter would hide the real child list at every depth — "**" names a computed leaf under a node (for example "${e.recursiveAnchor}${l}total").`),this._definitions.set(t,{recursivePath:t,suffix:n,get:o.get})}this._assertNoColliding(),this._assertNoConcreteCollision(n)}_assertNoConcreteCollision(e){for(const[t,n]of Object.entries(e)){if(Md(t)||Xd(n))continue;const e=this._matchExpansion(t);null!==e&&ee(`${Yd} "${t}" is already defined on the state, so the recursive getter "${e}" cannot expand to it. Rename one of them.`)}}_assertNoColliding(){const e=Array.from(this._definitions.values());for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++)Rd(this.spec,e[t].suffix,e[n].suffix)&&ee(`${Yd} "${e[t].recursivePath}" and "${e[n].recursivePath}" expand to the same concrete path at different depths (they differ by whole repetitions of "${this.spec.repeat}"). Rename one of them.`)}get hasDefinitions(){return this._definitions.size>0}conflictingRecursiveGetter(e){for(const t of this._definitions.values())if(jd(this.spec,t.suffix,e))return t.recursivePath;return null}recursiveGetterOwningPath(e){const t=this._ownerByPathInfo.get(e);if(void 0!==t)return t;const n=this.recursiveGetterOwning(e.path);return this._ownerByPathInfo.set(e,n),n}recursiveGetterOwning(e){const t=this._accessors.get(e);if(void 0!==t)return t.recursivePath;const n=Ld(e),o=this._ownerByPath.get(n);if(void 0!==o)return o;let s=null;if(n.startsWith(this.spec.anchor)){s=this._matchExpansion(n);for(let e=n.lastIndexOf(l);null===s&&e>this.spec.anchor.length;e=n.lastIndexOf(l,e-1))s=this._matchExpansion(n.slice(0,e))}return this._ownerByPath.set(n,s),s}_matchExpansion(e){for(const t of this._definitions.values())if(null!==zd(this.spec,t.suffix,e))return t.recursivePath;return null}materializeForPathInfo(e,t){if(0===this._definitions.size)return null;const n=this._accessorByPathInfo.get(t);if(void 0!==n)return n;const o=this.materializeFor(e,t.path);return this._accessorByPathInfo.set(t,o),o}materializeFor(e,t){const n=this._accessors.get(t);if(void 0!==n)return n;if(!t.startsWith(this.spec.anchor))return null;let o=null,s=0;for(const e of this._definitions.values()){const n=zd(this.spec,e.suffix,t);null!==n&&(null!==o&&ee(`"${t}" matches both "${o.recursivePath}" and "${e.recursivePath}".`),o=e,s=n)}return null===o?null:this._define(e,o,s,t)}_define(e,t,n,o){const s=e.findStateDescriptor(o);void 0===s||Xd(s)||ee(`"${o}" is already defined on the state, so the recursive getter "${t.recursivePath}" cannot expand to it. Rename one of them.`);const r=Object.freeze({recursivePath:t.recursivePath,depth:n}),i=t.get,a=function(){return i.call(this)};var l;return l=a,Jd.add(l),e.defineTreeAccessor(o,{get:a,enumerable:!1,configurable:!0}),this._registerListPaths(e,n),this._accessors.set(o,r),r}_registerListPaths(e,t){for(const n of function(e,t){const n=[];n.push(e.anchorList);for(let o=0;o<t;o++)n.push(Bd(e,o)+l+e.repeatList);return n}(this.spec,t))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),e.addListPath(n))}forgetGenerated(e,t){const n=new Set(this._accessors.keys());return Qd(e,t,n),n}concretePathAt(e,t){let n=this._concreteBySuffix.get(e);void 0===n&&(n=[],this._concreteBySuffix.set(e,n));let o=n[t];return void 0===o&&(o=Dd(this.spec,e,t),n[t]=o),o}accessorFor(e){return this._accessors.get(e)??null}get materializedPaths(){return new Set(this._accessors.keys())}}const eu="recursionSpec",tu="recursionRegistry",nu={order:5,validateEarly(e,t,n){const o=function(e){const t=e[V];if(void 0===t)return null;"object"==typeof t&&null!==t||ee(`[wcs/recursion-declaration-invalid] ${V} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(t);0===n.length&&ee(`[wcs/recursion-declaration-invalid] ${V} must declare exactly one anchor; it is empty.`),n.length>1&&ee(`[wcs/recursion-declaration-invalid] ${V} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];Kd("anchor",o),"string"!=typeof s&&ee(`[wcs/recursion-declaration-invalid] ${V} entry "${o}" must map to the repeating sub-path as a string (for example "children${l}${c}").`),Kd("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(l)),i=s.slice(0,s.lastIndexOf(l)),a=r+l+H;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(t);n.set(eu,o),n.set(tu,null===o?null:new Zd(o,t))},preCommit(e,t,n){const o=e.recursionRegistry;if(null!==o)for(const t of o.forgetGenerated(e,n.get("previousState")))e.addGeneratedPath?.(t);const s=n.get(tu)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",V)},apply(e,t,n){const o=n.get(eu)??null;null!==o&&e.addListPath(o.anchorList)}};let ou=!1;function su(){ou||(ou=!0,Gd||(Gd=!0,il("recursion",Ud)),dl("recursion",nu))}const ru={name:"recursion",install(){su()}};const iu={written:function(e,t,n){const o=e.bindableEventMap,s=o[t.path],r="string"==typeof s,i=r?s:t.segments.length>1?o[t.segments[0]]:void 0;if("string"!=typeof i)return;const a=e.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}};let au=!1;function lu(e){return function(){const t=this.stateElement;if(!t)return;if(!0!==t.initialized)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 cu(e){return function(t){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[e]=t})}):n.createState("writable",n=>{n[e]=t}))}}function du(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 uu(e){return e.startsWith("$")}function fu(e,t){return Object.keys(e).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof e[n].value;return"method"===t?o:!o})}function hu(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||ee(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||ee(`${t} entries must be non-empty strings.`),e.startsWith("$")&&ee(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&ee(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function pu(e){const t=hu(e,R)??[],n=hu(e,j)??[],o=fc(e),s=function(e){const t=e[z];return"object"!=typeof t||null===t?new Set:new Set(Object.keys(t))}(e),r=[];for(const e of t){const t=o[e];if(void 0===t){if(s.has(e)){r.push(e);continue}ee(`${R} entry "${e}" is not declared on the state.${ie(e,fu(o,"value"))}`)}"function"==typeof t.value&&ee(`${R} entry "${e}" is a method. Declare it in ${j} instead.`)}for(const e of n){const t=o[e];void 0===t&&ee(`${j} entry "${e}" is not declared on the state.${ie(e,fu(o,"method"))}`),"function"!=typeof t.value&&ee(`${j} entry "${e}" is not a method. Declare it in ${R} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}function mu(e,t,n){const s=e.tagName.toLowerCase();s.includes("-")||ee(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Ve(e);null!==r&&"function"==typeof r.define||ee(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&ee(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const e of Array.from(t.childNodes))i.content.appendChild(a.importNode(e,!0));const l=t.mode,{bindables:c,commands:d,streamBackedBindables:u}=pu(n),f=c.length>0||d.length>0?function(e,t,n=[]){const o={protocol:"wc-bindable",version:1,properties:t.map(t=>({name:t,event:`${e}:${t}-changed`,getter:e=>e.target[t]})),inputs:t.map(e=>({name:e}))};if(0===n.length)return o;const s=n.map(e=>({name:e,async:!0}));return{...o,commands:s}}(s,c,d):null,h=c.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(s,c):{},p=o.tagNames.state,m=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=f;static bindableEventMap=h;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(J))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const e=Ve(this._shadow);return null!==e&&He(e,this._shadow),this._shadow}connectedCallback(){const e=this._ensureShadow();if(null!==e&&Object.keys(m.bindableEventMap).length>0){const t=e.querySelector(p);t?(au||(au=!0,il("dcc",iu)),t.setBindableEventMap(m.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${s}" declares ${R} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=fc(n);for(const[e,t]of Object.entries(g)){if(uu(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=du(e,o)}else n.get=lu(e),n.set=cu(e);Object.defineProperty(m.prototype,e,n)}for(const e of u)Object.defineProperty(m.prototype,e,{configurable:!0,enumerable:!0,get:lu(e),set:cu(e)});r.define(s,m)}async function gu(e,t,n){const o=e;try{o.hasAttribute("bind-component")&&ee(`"bind-component" cannot be used inside a [${J}] host. DCC state comes from the template, not from a component property.`);const s=await async function(e,t){try{if(e.hasAttribute("src")){const t=e.getAttribute("src");if(t.endsWith(".js"))return await Qa(t);ee(`DCC: Unsupported src type: ${t}`)}const n=e.querySelector('script[type="module"]');if(n)return await Xa(n,t.tagName.toLowerCase());ee(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}catch(e){ee(`DCC: Failed to load state: ${e}`)}}(o,t);mu(t,n,s),e.markTreeless(),e.markInitialized(),e.clearConnectedRootNode(),e.settleInitialization()}catch(t){e.failInitializeLoudly(t)}}const yu={order:10,connecting(e){const t=e.parentNode;return t instanceof ShadowRoot&&t.host.hasAttribute(J)?gu(e,t.host,t):null}};let wu=!1;const bu=new WeakMap;function vu(e,t,n){let o=bu.get(e);void 0===o&&(o=new Map,bu.set(e,o));const s=o.get(t);null!=s&&ee(`Volume slot "${t}" is already mounted on this tree.`),o.set(t,n)}function $u(e,t){if(null===e)return!1;const n=bu.get(e);if(void 0===n||0===n.size)return!1;for(const e of n.keys())if(t===e||t.startsWith(e+l)||e.startsWith(t+l))return!0;return!1}const xu=new WeakMap;const Su=[];function Pu(e,t,n,o){if(t.length>0){const s=n.split(l),r=xc(t,s);if(null!==r)return o&&r.readonly&&ee(`[wcs/mount-readonly] volume "${e}" cannot write "${n}": it is injected read-only ("${S}.${r.innerSegments.join(l)}#${g}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${g} from the injection.`),Sc(r,s)}return e+l+n}function Iu(e,t,n){for(const e of t){const t=e.outerPathInfo.path;if(n===t)return e.innerSegments.join(l);if(n.startsWith(t+l))return e.innerSegments.join(l)+n.slice(t.length)}return n===e?"":n.startsWith(e+l)?n.slice(e.length+1):null}function Nu(e,t,n=Su){return new Proxy({},{get(o,s){if("string"==typeof s&&"then"!==s){if("$"===s[0]){if("$postUpdate"===s||"$getAll"===s){const o=s;return(s,...r)=>t[o](Pu(e,n,s,!1),...r)}return"$setAll"===s?(o,...s)=>t.$setAll(Pu(e,n,o,!0),...s):"$resolve"===s?(o,...s)=>t.$resolve(Pu(e,n,o,s.length>1),...s):t[s]}return t[Pu(e,n,s,!1)]}},set:(o,s,r)=>("string"!=typeof s||(t[Pu(e,n,s,!0)]=r),!0),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const ku=new WeakMap,_u=[];const Au=new WeakMap,Cu=new WeakSet;function Eu(e){console.error(`[@wcstack/state] volume "${e.mountPath}" was not grafted — the root state element on this root node failed to initialize (its own diagnostic is reported separately). The volume is not at fault: fix the root <wcs-state>.`),e.onGrafted(null)}let Mu=null;const Ou=new WeakMap,Tu=new Set;function Ru(e,t,n,o){let s=Ou.get(e);if(void 0===s){if(!o)return null;s=new Map,Ou.set(e,s)}let r=s.get(t);if(void 0===r){if(!o)return null;r=new Map,s.set(t,r)}let i=r.get(n);if(void 0===i){if(!o)return null;i={holders:new Set,byListIndex:new WeakMap,noIndex:null},r.set(n,i)}return i}function ju(e,t){if(!e.component.isConnected)return!1;const n=mt(e.component)?.listIndex??null;if(null===t)return null===n;let o=n;for(;null!==o;){if(o===t)return!0;o=o.parentListIndex}return!1}function Lu(e,t,n,o){const s=Ru(e,t,n,!1);if(null===s)return null;const r=null===o?s.noIndex:s.byListIndex.get(o)??null;if(null!==r){const e=function(e,t){const n=e.ref.deref();return void 0!==n&&ju(n,t)?n:null}(r,o);if(null!==e)return{record:e,entry:r.entry}}let i=null,a=null;for(const e of s.holders){const r=e.ref.deref();void 0!==r?ju(r,o)&&(null!==a&&ee(`[wcs/mount-export-ambiguous] "${t}${l}${n}" is exported by two mounted components on the same instance: <${a.component.tagName.toLowerCase()}> and <${r.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),i=e,a=r):s.holders.delete(e)}return null===i||null===a?null:(null===o?s.noIndex=i:s.byListIndex.set(o,i),{record:a,entry:i.entry})}function Wu(e){const t=e.parentStateElement,n=mt(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[Ct](n,()=>{e.$postUpdate(o.exportedPath)})})}const Du=new WeakMap;class Bu{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(e,t,n,o,s,r){this.record=e,this.markerParentPath=t,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(e){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(e)?.accessorName}accessorAddress(e){return mn(oe(this.markerParentPath+l+e),this.listIndex)}get(e,t,n){if("string"!=typeof t)return Reflect.get(e,t);if("then"===t)return;if("$"===t[0]){if("$postUpdate"===t)return e=>{this.receiver.$postUpdate(Wc(this.record,e))};if("$getAll"===t||"$setAll"===t||"$resolve"===t){const e=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===t)return(t,s,...r)=>{const i=r.length>0?Lc(e,t):Wc(e,t),a=Bc(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const s=t;return(t,r,...i)=>{const a="$setAll"===s?Lc(e,t):Wc(e,t),l=Bc(0,t,a,r,n);return o[s](a,l,...i)}}return this.receiver[t]}const o=this.accessorNameFor(t);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(t));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return yl(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(n)}return this.receiver[Wc(this.record,t)]}set(e,t,n,o){if("string"!=typeof t)return Reflect.set(e,t,n);const s=this.accessorNameFor(t);if(void 0!==s){this.record.setterKeys.has(s)||ee(`Cannot write to "${s}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(t)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,s,n,o)}finally{this.handler.endUntrack(),this.handler.popAddress()}}return this.isBase&&Object.prototype.hasOwnProperty.call(e,t)?(e[t]=n,!0):(this.receiver[Lc(this.record,t)]=n,!0)}has(e,t){if("string"!=typeof t)return Reflect.has(e,t);if("$"===t[0]||"#"===t[0])return!1;if(void 0!==this.accessorNameFor(t))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return!0;if("function"==typeof this.record.stateObject[t])return!0}try{return Wc(this.record,t),!0}catch{return!1}}}function zu(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=Du.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Du.set(e,n)),null===t)return n.noIndex??={...e.privateSnapshot};let o=n.byListIndex.get(t);return void 0===o&&(o={...e.privateSnapshot},n.byListIndex.set(t,o)),o}(e,t.listIndex):{};return new Proxy(i,new Bu(e,s,t.listIndex,r,n,o))}function Fu(e){const t=e.parentStateElement,n=(t,n)=>{const o=mt(e.component);let s;return t[Ct](o,()=>{s=n()}),s};return new Proxy({},{get(o,s){if("string"!=typeof s||"then"===s)return;if("$getAll"===s||"$setAll"===s||"$resolve"===s||"$postUpdate"===s)return function(e,t,n){const o=e.parentStateElement,s=(e,t)=>{let s;return o.createState(e,e=>{s=n(e,()=>t(e))}),s};return"$postUpdate"===t?t=>s("readonly",n=>n.$postUpdate(Wc(e,t))):(n,o,...r)=>{const i="$setAll"===t||"$resolve"===t&&r.length>0,a=i?Lc(e,n):Wc(e,n),l=mt(e.component)?.listIndex.indexes??[],c=Bc(0,n,a,"$resolve"===t?o??[]:o,l);return s(i?"writable":"readonly",e=>e[t](a,c,...r))}}(e,s,n);let r;return t.createState("readonly",t=>{r=n(t,()=>t["$"===s[0]?s:Wc(e,s)])}),r},set:(o,s,r)=>("string"!=typeof s||t.createState("writable",t=>{n(t,()=>{t["$"===s[0]?s:Lc(e,s)]=r})}),!0),has(t,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(e.stateObject,n))return!0;try{return Wc(e,n),!0}catch{return!1}}})}function qu(e,t){const n=function(e){return zc.get(e)??null}(t);var o,s;null!==n&&n.stateProp!==e.stateProp&&ee(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${e.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&cs(t).dispose(),function(e,t){Kc(),zc.set(e,t),Hc.set(t,e);let n=qc.get(t.parentStateElement);void 0===n&&(n=new Map,qc.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=Fc.get(t.component);void 0===o&&(o=new Map,Fc.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&Vc.register(t,{byMarker:n,marker:t.marker,getterPaths:t.parentStateElement.getterPaths,addedGetterPaths:t.addedGetterPaths}),t.parentStateElement.markHasMounts?.()}(t,e),t instanceof ShadowRoot&&function(e,t){const n=fa.get(e);if(void 0!==n){if(n===t)return;ee("A state tree is already registered on this root.")}fa.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>Dc(e,t,n);Y(t);const o=mt(e.component);Ba(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),sa(t,o,n)}(e,t),function(e){if(e.exports.size>0||null===e.rootEntry)return;const t=new Set([...e.getterKeys,...e.setterKeys]);for(const n of t){let t;try{t=Wc(e,n)}catch{continue}const o=t.indexOf(l+e.marker);if(-1===o)continue;const s=t.slice(0,o+1+e.marker.length),r=t.slice(s.length+1),i=t.slice(0,o)+l+r,a=oe(i);if(a.wildcardCount!==e.delta)continue;const c={markerTerminalPath:s,suffix:r,markerPath:t,exportedPath:i};e.exports.set(i,c),Ru(e.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:c}),e.parentStateElement.addDynamicDependency(t,i),hc?.markExported(e.parentStateElement,i)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=mt(e.component);if(e.delta>0&&null===t)return;const n=e.component.tagName.toLowerCase();for(const o of e.exports.values()){const s=`${n}|${o.exportedPath}`;if(Tu.has(s))continue;const r=oe(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Ct](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Tu.add(s),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${e.stateProp}.${o.suffix} is exported at "${o.exportedPath}" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`))}}(e),Wu(e),o=t,s=Promise.resolve(),ha.set(o,s),s.then(()=>ba(o),()=>{})}function Vu(e,t){const n=cs(t),o=mt(e.component);n.forEachActiveBindingNode(e=>gt(e,o));oa(n.rebindAddresses()),Wu(e)}function Hu(e,t){if(function(e){const t=qc.get(e);return void 0!==t&&t.size>0}(t))for(const n of Jc(t)){if(!Uu(n.component,e))continue;const t=Uc(n);null!==t&&Vu(n,t)}}function Uu(e,t){for(let n=t.firstNode;null!==n;n=n.nextSibling){if(n===e||n.contains(e))return!0;if(n===t.lastNode)break}return!1}const Gu={read(e,t,n,o){if(!0===e.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const s=Xc(e,t.pathInfo.path);if(null!==s)return zu(s,t,n,o)}return ol},readMissing(e,t,n,o,s){if(null===n){if($u(e.rootNode??null,t.pathInfo.path))return;return ol}if(!0===e.hasMounts){const n=Lu(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s){const r=zu(e,mn(oe(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(n.record,n.entry,t.listIndex,o,s)}return ol},write(e,t){if(!0===e.hasGraftedVolumes){const n=t.pathInfo.path,o=function(e,t){const n=xu.get(e);if(void 0===n||0===n.size)return null;const o=t+l;for(const e of n)if(e.startsWith(o))return e;return null}(e,n);null!==o&&ee(`Cannot replace "${n}" wholesale: a volume is mounted at "${o}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${o}" itself, or individual fields inside "${n}", instead.`)}return ol},writeMissing(e,t,n,o,s,r,i){if(!0===e.hasMounts){const n=Lu(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s,r){const i=zu(e,mn(oe(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(n.record,n.entry,t.listIndex,s,r,i)}return ol},indexShift(e,t){const n=e.stateElement,o=t.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const e=Xc(n,o);if(null!==e)return function(e,t){const n=t.lastIndexOf("#");if(-1===n)return e.delta;const o=t.indexOf(l,n);if((-1===o?t.slice(n):t.slice(n,o))!==e.marker)return e.delta;const s=-1===o?t:t.slice(0,o),r=-1===o?"":t.slice(o+1),i=e.accessorBySuffixByMarkerParent.get(s)?.get(r);return void 0!==i?i.indexShift:e.delta}(e,o)}return 0},handlerScope(e,t,n,o,s){if(!0!==e.hasMounts)return s;const r=function(e,t){let n=e;for(;null!==n&&n!==t;){const e=zc.get(n);if(void 0!==e)return e;n=n.parentNode}return zc.get(t)??null}(t,n);if(null===r)return s;const i=r.indexShiftByLoopElementPath.get(o.pathInfo.path);return void 0!==i?s-i:0},updated(e,t,n){const o=function(e){return ku.get(e)??_u}(e);for(const s of o){const o=new Set,r={};for(const n of t){if(n.absolutePathInfo.stateElement!==e)continue;const t=n.absolutePathInfo.pathInfo.path;if(-1!==t.indexOf("#"))continue;const i=Iu(s.mountPath,s.injections,t);if(null===i||""===i)continue;o.add(i);const a=n.absolutePathInfo.pathInfo.wildcardCount;if(a>0&&null!==n.listIndex){const e=Zt(n.listIndex,a);(r[i]??=[]).push(e)}}if(o.size>0)try{s.callback.call(Nu(s.mountPath,n,s.injections),Array.from(o),r)}catch(e){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,e)}}},suppressPathDiagnostic:(e,t)=>$u(!1===e.isConnected?null:e.rootNode??null,t),rowReused(e,t){Hu(t,e)}};let Ku=!1;const Ju=new WeakMap;function Xu(e){let t=Ju.get(e);return void 0===t&&(t={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},Ju.set(e,t)),t}function Qu(e,t){null!==t.slotRootNode&&(!function(e,t,n){const o=bu.get(e);o?.get(t)===n&&o.set(t,null)}(t.slotRootNode,t.mountPath,e),t.slotRootNode=null)}function Yu(e,t,n){if(t.slotRootNode===n)return!0;const s=t.mountPath;try{vu(n,s,e)}catch{return console.error(`[@wcstack/state] <${o.tagNames.state} mount="${s}"> will not graft: another volume already holds the "${s}" slot on this root. Keep one volume per mount path.`),!1}return ga(n)?.markHasVolume?.(),t.slotRootNode=n,!0}async function Zu(e,t){const n=e,s=e.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(e){0===e.length&&ee('"mount" requires a non-empty tree path.');const t=oe(e);for(const n of t.segments)0===n.length&&ee(`"mount" path "${e}" has an empty segment.`),n===c&&ee(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&ee(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(r),i=function(e,t){const n=[],s=new Set;for(const r of Ce(e)){if(r.propSegments[0]!==S)continue;const e=r.propSegments.slice(1),i=r.statePathInfo,a=e=>ee(`[wcs/mount-path-invalid] <${o.tagNames.state} mount="${t}"> "${r.propName}: ${r.statePathName}": ${e}`);1===e.length&&e[0]&&e[0]!==c&&"$"!==e[0][0]&&"#"!==e[0][0]||a(`inject one key at a time ("${S}.<key>: path"); change "mount" to move the whole volume.`),(i.wildcardCount>0||"$"===i.path[0]||"#"===i.path[0])&&a("the injected path must be a static path on the root tree (a volume has no loop context)."),(r.inFilters.length>0||r.outFilters.length>0)&&a("an injection takes no filters."),r.propModifiers.some(e=>e!==g)&&a(`an injection accepts only #${g}.`),s.has(e[0])&&a(`"${e[0]}" is injected twice.`),s.add(e[0]),n.push({innerSegments:e,outerPathInfo:i,readonly:r.propModifiers.includes(g)})}return n}(n.getAttribute(o.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&ee('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),vu(s,r,e),ga(s)?.markHasVolume?.(),t.mountPath=r,t.slotRootNode=s}catch(t){throw e.settleInitialization(),t}t.initializing=!0,null===ga(s)&&function(e,t){const n=()=>{if(null!==ga(e))return;const n=e.querySelectorAll(o.tagNames.state);for(const e of n)if(!e.hasAttribute("mount")&&!e.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${t}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${o.tagNames.state}> to this root node (an empty <${o.tagNames.state}></${o.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},s=e.ownerDocument??e;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(s,r);const a=n=>{t.graftInfo=n,e.markInitialized(),null===n&&Qu(e,t),e.settleInitialization()};let l;try{l=await e.loadStateFromSource()}catch(e){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,e),void a(null)}const d=e.connectedRootNode??null;null!==d&&Yu(e,t,d)?function(e,t,n,o,s,r,i=[]){const a={mountPath:n,volumeState:o,injections:i,onGrafted:s,acquireSlot:r};if(null!==t)return void ip(t,a);lp(),function(e,t){if(Cu.has(e))return void Eu(t);let n=Au.get(e);void 0===n&&(n=[],Au.set(e,n)),n.push(t)}(e,a)}(d,ga(d),r,l,a,()=>Yu(e,t,d),i):a(null)}const ef={order:20,connecting(e){if(!e.hasAttribute("mount"))return null;const t=Xu(e);if(t.initializing){const n=e.connectedRootNode;if(null!=n&&t.detachedFrom===n)try{vu(n,t.mountPath,e),ga(n)?.markHasVolume?.(),t.slotRootNode=n}catch{}return t.detachedFrom=null,ic}return Zu(e,t)},reconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=Xu(e),n=e.connectedRootNode??null;return null!==t.graftInfo&&null!==n&&ga(n)===t.graftInfo.rootStateElement&&op(t.graftInfo,"$connectedCallback"),!0},replacingState(e){if(!0!==Ju.get(e)?.initializing)return;const t=e.getAttribute("mount");ee(`Cannot replace the state of <${o.tagNames.state} mount="${t}"> after it has loaded: a volume's data is copied into the root tree when it grafts, so a new state would never reach the page. Write the paths under "${t}" on the root state instead.`)},initializeFailed(e,t){!function(e){Cu.add(e);const t=Au.get(e);if(void 0!==t){Au.delete(e);for(const e of t)Eu(e)}}(t)},initializeFailureCleared(e,t){!function(e){Cu.delete(e)}(t)},disconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=Xu(e);return null!==t.graftInfo&&op(t.graftInfo,"$disconnectedCallback"),!0!==e.initialized&&(t.detachedFrom=t.slotRootNode,Qu(e,t)),e.clearConnectedRootNode(),!0}};let tf=!1;const nf=new WeakMap;function of(e,t){let n=nf.get(e);n||(n=new Set,nf.set(e,n)),n.add(t)}const sf=new WeakMap;const rf=new WeakMap,af=new WeakMap;const lf=new WeakMap;const cf={isComplete:function(e,t){return!0===nf.get(e)?.has(t)},isDeclared:function(e,t){return!0===sf.get(e)?.has(t)},rememberOverwrittenObject:function(e,t,n){let o=rf.get(e);o||(o=new Map,rf.set(e,o)),o.has(t)||o.set(t,n)},recordInjectedKey:function(e,t,n){let o=af.get(e);o||(o=new Map,af.set(e,o));let s=o.get(t);s||(s=new Set,o.set(t,s)),s.add(n)},rememberOverwrittenValue:function(e,t,n,o){let s=lf.get(e);s||(s=new Map,lf.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}};function df(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)}const uf=new WeakMap;class ff{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=uf.get(e);return n?n.get(t)??null:null}(e,t)??ee("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 hf=e=>()=>e;function pf(e,t,n,o){!function(e,t,n){let o=uf.get(e);o||(o=new Map,uf.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(df(o));const s=function(e,t){const n=new ff(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:hf(s),enumerable:!0,configurable:!0}),of(t,n),mf(t,n)}function mf(e,t){if(T in e){const n=e[T];"function"==typeof n?n.call(e,t).catch(e=>{ee(`Error in ${T}: ${e instanceof Error?e.message:String(e)}`)}):ee(`${T} is not a function.`)}}const gf=new Set;function yf(e,t){gf.has(e)||(gf.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function wf(e){const t=e.rootEntry,n=mt(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[Ct](n,()=>{o=e[t.outerPathInfo.path]})}),o}const bf=new WeakMap;function vf(e,t){e.landInitialization(),ee(t)}async function $f(e,t){const n=e;if(n.hasAttribute("bind-component")){const i=n.parentNode,a=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,l=a?Fe(a):null;null!==a&&null!==l||ee(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(o.bindAttributeName)||vf(e,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const c=["state","src","json"].filter(e=>n.hasAttribute(e));null!==n.querySelector('script[type="module"]')&&c.push('<script type="module">'),c.length>0&&ee(`"bind-component" cannot be combined with ${c.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const d=n.getAttribute("bind-component");!function(e,t){let n=sf.get(e);n||(n=new Set,sf.set(e,n)),n.add(t)}(a,d);const u=Ve(a);null===u&&ee(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(o.bindAttributeName)&&await De(a),d in a||ee(`Component does not have property "${d}" for state binding.`);let f=a[d];"object"==typeof f&&null!==f||ee(`Component property "${d}" is not an object for state binding.`);const h=function(e,t){const n=rf.get(e);if(!n)return;const o=n.get(t);return n.delete(t),o}(a,d);if(void 0!==h&&function(e,t){if(!e.hasAttribute(o.bindAttributeName))return!1;const n=ot(e);if(null===n)return!1;for(const e of n)if(1===e.propSegments.length&&e.propSegments[0]===t)return!0;return!1}(a,d)&&(a[d]=h,f=h),t.boundComponent=a,t.boundComponentStateProp=d,e.setBoundComponent(a,d),i instanceof ShadowRoot||(ot(a)??[]).some(e=>e.propSegments[0]===d)||vf(e,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${d}: path").`),a.hasAttribute(o.bindAttributeName)){const o=(ot(a)??[]).filter(e=>e.propSegments[0]===d);if(o.length>0){const c=ga(a.getRootNode())??vf(e,`No state tree found on this root for mount host <${l}>.`);let u=(s=a,r=d,Fc.get(s)?.get(r)??null);const h=null!==u;if(null===u&&(function(e,t,n){const o=lf.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;lf.get(e).delete(t)}}(a,d,f),u=_c(a,d,o,c,f,function(e,t){return af.get(e)?.get(t)}(a,d)),function(e){const t=Object.keys(e.privateSnapshot);if(0===t.length)return;const n=e.component.tagName.toLowerCase(),o=e.stateProp;let s,r=!1;for(const i of t){if(null===e.rootEntry)continue;if(r||(s=wf(e),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const t=e.rootEntry.outerPathInfo.path;yf(`${n}|${o}|${i}|root`,`<${n}>.${o}.${i} is private and hides the mounted tree key "${t}.${i}" (${o}: ${t}). Remove the default to read the tree, or rename it to keep it private.`)}}(u)),t.mountRecord=u,n.parentNode!==i)return;try{qu(u,i instanceof ShadowRoot?i:a)}catch(t){throw e.landInitialization(),t}if(!h){const e=Fu(u);Object.defineProperty(a,d,{get:()=>e,enumerable:!0,configurable:!0}),of(a,d)}return mf(a,d),function(e){const t=Ic.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(H)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;Nc.has(n)||(Nc.add(n),console.warn(`[@wcstack/state] [wcs/mount-dollar-declaration] <${n.split("|")[0]}>.${e.stateProp} declares ${t.join(", ")}, which mounted components do not run. Declare them on the root state instead (a volume <wcs-state mount="..."> can host $watch / $listKeys / $updatedCallback; $recursion and "**" getters expand against the root tree). See docs/state-mount-design.md §4-6.`))}(u),void kc(u,"$connectedCallback")}}pf(e,t.boundComponent,t.boundComponentStateProp,f)}var s,r}const xf={order:30,preparing(e){if(!e.hasAttribute("bind-component"))return null;const t=function(e){let t=bf.get(e);return void 0===t&&(t={boundComponent:null,boundComponentStateProp:null,mountRecord:null},bf.set(e,t)),t}(e);return $f(e,t).then(()=>null!==t.mountRecord&&(e.markInitialized(),e.settleInitialization(),!0))},reconnecting(e){const t=bf.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord,o=e.parentNode;return queueMicrotask(()=>{null!=e.connectedRootNode&&Vu(n,o)}),kc(n,"$connectedCallback"),!0},disconnecting(e){const t=bf.get(e);return void 0!==t&&null!==t.mountRecord&&(kc(t.mountRecord,"$disconnectedCallback"),Wu(t.mountRecord),e.clearConnectedRootNode(),!0)}};let Sf=!1;function Pf(){Sf||(Sf=!0,cc("bindComponent",xf),us=cf)}const If=new WeakMap,Nf=new Set,kf=new Set;function _f(e){return e.byFromPath.size>0||e.byResetPath.size>0}function Af(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function Cf(e){return If.get(e)}function Ef(e){Mf(e),If.delete(e)}function Mf(e){Nf.delete(e),kf.delete(e)}const Of=new WeakMap,Tf=new WeakMap,Rf=new Set,jf=new Map;function Lf(e){return Of.get(e)??jf}function Wf(e){Rf.add(e),function(e){const t=If.get(e);void 0!==t&&(_f(t)&&Nf.add(e),function(e){return e.eventResetByPath.size>0}(t)&&kf.add(e))}(e)}const Df=new Map;function Bf(e){return Tf.get(e)??Df}function zf(e){0===e.length&&ee(`[wcs/watch-declaration-invalid] ${F} entry name must be a non-empty state path.`),e.startsWith("$")&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${e}" must not start with "$" (reserved namespace).${ae}`),e.includes("@")&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${ae}`),e in Object.prototype&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const t=oe(e);for(const n of t.segments)0===n.length&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${e}" has an empty path segment.${ae}`);return t.wildcardCount>d&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function Ff(e,t){const n=t[F];if(void 0===n)return null;"object"==typeof n&&null!==n||ee(`[wcs/watch-declaration-invalid] ${F} must be an object mapping state paths to handler functions.${ae}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${t}" must be a function.${ae}`);const n=zf(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){Of.set(e,t)}(e,o),s.size>0?s:null}let qf=0,Vf=0;function Hf(e){qf=e+1}function Uf(){qf=0}function Gf(){qf>Vf&&(Vf=qf)}const Kf=new WeakMap;function Jf(e,t,n){let o=Kf.get(e);void 0===o&&(o=new Map,Kf.set(e,o)),o.set(t,n)}const Xf=new Map;function Qf(e,t){Xf.has(e)||Xf.set(e,t)}function Yf(e){return Xf.get(e)}const Zf={writeObserve(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||Qf(n,o)},swapped(e,t,n){var o;o=n,Xf.has(o)&&Qf(t,Yf(n))}};function eh(e){for(let t=e;null!==t;t=t.parentListIndex)if(Ts(t))return!0;return!1}function th(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[Et](mn(t.wildcardParentPathInfos[i],r)),l=js(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=Yt(o,i,t.wildcardCount);if(l!==c&&!Es(l,c)){if(Ts(c))return"gone";s="replaced"}r=l}return s}function nh(e,t,n){const o=new Map;for(const s of n){const n=th(e,t,s);if("gone"===n)continue;const r="current"===n?1:0,i=s.indexes.join(","),a=o.get(i);(void 0===a||r>a.rank)&&o.set(i,{row:s,rank:r})}return Array.from(o.values(),e=>e.row)}const oh=new Set;function sh(e){oh.delete(e)}function rh(){return oh}const ih=Symbol("wcs-stream-last-notified-uncertain"),ah=new WeakMap;function lh(e,t){const n=ah.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function ch(e,t){const n=ah.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:ih,error:Object.is(o.error,null)?null:ih})}const dh=new WeakMap;function uh(e){return dh.get(e)??new Map}function fh(e){sh(e);const t=dh.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,ch(e,n.name)}const hh=new WeakSet;let ph=0;function mh(e){return Cf(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function gh(e){if(0===kf.size)return;if(t=e.absolutePathInfo.stateElement,!kf.has(t))return;var t;const n=mh(e);if(void 0!==n)for(const e of n)yh(e)}function yh(e){hh.has(e)||(hh.add(e),ph++)}function wh(e){return!!hh.delete(e)&&(ph--,!0)}const bh=/^(?:0|[1-9]\d*)$/;function vh(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function $h(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return null;const t=Object.getPrototypeOf(e);if(Array.isArray(e)){return t===Array.prototype&&Reflect.ownKeys(e).every(t=>"length"===t||"string"==typeof t&&bh.test(t)&&vh(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&vh(e,t))?"object":null}function xh(e,t){const n=$h(e);if(null===n)return e;const o=e,s=t.get(o);if(void 0!==s)return s;let r;r="array"===n?new Array(e.length):null===Object.getPrototypeOf(e)?Object.create(null):{},t.set(o,r);for(const e of Object.keys(o))r[e]=xh(o[e],t);return r}function Sh(e){return xh(e,new Map)}function Ph(e,t,n){if(Object.is(e,t))return!0;const o=$h(t);if(null===o||"object"!=typeof e||null===e)return!1;const s=e,r=t;if("array"===o){if(!Array.isArray(e)||e.length!==t.length)return!1}else if(Array.isArray(e)||Object.keys(s).length!==Object.keys(r).length)return!1;if($h(e)!==o)return!1;let i=n.get(s);if(void 0===i)i=new Set,n.set(s,i);else if(i.has(r))return!0;if(i.add(r),"array"===o){for(let t=0;t<e.length;t++)if(!Ph(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&Ph(s[e],r[e],n))}function Ih(e,t){return Ph(e,t,new Map)}const Nh=new WeakMap;function kh(e,t){if("function"!=typeof t)return;const n=Nh.get(t);void 0===n?Nh.set(t,new Set([e])):n.add(e)}const _h={"read-source":e=>`${q} could not read a "from" value for "${e}". That landing was not folded; the other landings of the batch still were.`,"read-output":e=>`${q} could not read the output "${e}". Nothing was folded or written.`,threw:e=>`${q} fold for "${e}" threw. The output was not written.`,"returned-promise":e=>`${q} fold for "${e}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:e=>`${q} could not write the output "${e}".`},Ah={"read-source":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function Ch(e,t,n){null!==yt&&yt({type:"state:watch-error",phase:t,path:`${q}.${e}`,error:n})}function Eh(e,t,n){console.error(`[@wcstack/state] ${_h[n](e)}`,t),Ch(e,Ah[n],t)}function Mh(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function Oh(e,t){t.then(void 0,()=>{}),Eh(e,new TypeError(`${q} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const Th=new WeakSet;const Rh=Object.freeze([]);function jh(e,t,n){let o=e.get(n);return void 0===o&&(o={stateElement:t,entry:n,rows:[],reset:!1},e.set(n,o)),o}function Lh(e,t){let n=0;for(;n<e.indexes.length-1&&e.indexes[n]===t.indexes[n];)n++;return e.indexes[n]-t.indexes[n]}function Wh(e,t){return t.has(e.stateElement)&&!0===Cf(e.stateElement)?.entries.has(e.entry)}function Dh(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>Bh(n,e))||wh(t)}function Bh(e,t){return Ys().hasQueuedPath(e,t)}function zh(e,t){!function(e,t,n){if(0!==ph)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=mh(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||wh(t)}}(e,t,Bh)}function Fh(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function qh(e,t,n){if(!Wh(e,n))return Dh(e),null;const{stateElement:o,entry:s}=e;if(e.reset)return{group:e,next:s.initial};const r=s.source;if(function(e,t){for(const n of t.pathInfo.cumulativePaths)if(e.getterPaths.has(n))return!0;return!1}(o,r))return function(e,t,n){if(Th.has(e))return;Th.add(e);const o=`[wcs/scan-source-computed] ${q} entry "${t}" from "${n}" is now backed by a getter (registered after the declaration, e.g. by a volume). A getter re-evaluates whenever its inputs change, so this scan stopped folding. Fold the plain value the getter reads instead.`;console.error(`[@wcstack/state] ${o}`),Ch(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=uh(e).get(t);if(void 0===o)return!1;for(const e of o.depAddresses)if(n.has(e))return!0;return!1}(o,r.pathInfo.segments[0],t))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",t=>{const n=t[s.name],o=0===r.pathInfo.wildcardCount?e.rows:nh(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(Lh)){let n;try{n=Fh(t,r,e)}catch(e){Eh(s.name,e,"read-source");continue}const o=a(l,n,Yf(e.absAddress),...e.indexes);if(Mh(o))return void Oh(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){Eh(s.name,e,i.failure)}return i.plan}function Vh(e,t){const{group:n}=e;if(!Wh(n,t))return void Dh(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||wh(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!Ih(o,s.initial):!Object.is(o,e.next)){const o=n.reset?Sh(s.initial):e.next;t[s.name]=o,kh(s.name,o)}})}catch(e){Eh(s.name,e,"write")}}function Hh(e,t,n){if(zh(e,t),0===Nf.size)return Rh;const o=new Map;for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=Cf(e);if(void 0===s)continue;const r=n.absolutePathInfo.pathInfo,i=s.byFromPath.get(r.path);if(void 0!==i){let t=[];if(r.wildcardCount>0){if(null===n.listIndex)continue;t=Zt(n.listIndex,r.wildcardCount)}for(const s of i)jh(o,e,s).rows.push({absAddress:n,indexes:t})}const a=s.byResetPath.get(r.path);if(void 0!==a)for(const t of a)jh(o,e,t).reset=!0}if(0===o.size)return Rh;const s=Array.from(o.values()).sort((e,t)=>e.entry.order-t.entry.order),r=[];Hf(n);try{for(const n of s){const o=qh(n,e,t);null!==o&&r.push(o)}}finally{Uf()}return r}function Uh(e){tp(),(0!==Lf(e).size||0!==Bf(e).size||function(e){const t=If.get(e);return void 0!==t&&_f(t)}(e))&&(Wf(e),function(e){const t=[];for(const n of Lf(e).values())Gh(e,n)&&t.push(n);for(const n of Bf(e).values())for(const o of n)Gh(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{Jf(e,Ut(e,o.pathInfo,null),n[o.path])}catch(t){Jh(e,o.path,"prime",t)}})}(e))}function Gh(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const Kh={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Jh(e,t,n,o){console.error(`[@wcstack/state] $watch ${Kh[n]} "${t}" threw.`,o),null!==yt&&yt({type:"state:watch-error",phase:n,path:t,error:o})}function Xh(e){const t=Rf;try{if(0===t.size)return void zh(e,t);const n=function(){const e=Vf;return Vf=0,e}();if(n>32){zh(e,null);const t=Array.from(e,e=>e.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; $scan folds and $watch handlers for this batch were skipped.",{maxDepth:32,paths:t}),void(null!==yt&&yt({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}!function(e,t,n){if(0!==e.length){Hf(n);try{for(const n of e)Vh(n,t)}finally{Uf()}}}(Hh(e,t,n),t,n),function(e,t,n){const o=[];for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=n.absolutePathInfo.pathInfo.path,r=Lf(e).get(s),i=Bf(e).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const t of a){let s=[];if(t.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=Zt(n.listIndex,t.pathInfo.wildcardCount)}o.push({stateElement:e,entry:t,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(Yh);const s=function(e){let t=null;for(let n=0;n<e.length;n++){const o=e[n];if(0===o.entry.pathInfo.wildcardCount)continue;const s=e[n-1];(eh(o.absAddress.listIndex)||s?.entry===o.entry&&Qh(s.indexes,o.indexes))&&(t??=new Set).add(o.entry)}if(null===t)return e;const n=new Set;for(const o of t){const t=e.filter(e=>e.entry===o),s=t[0].stateElement;try{s.createState("readonly",e=>{const s=new Set(nh(e,o.pathInfo,t));for(const e of t)s.has(e)||n.add(e)})}catch(e){Jh(0,o.path,"evaluate",e);for(const e of t)n.add(e)}}return e.filter(e=>!n.has(e))}(o);Hf(n);try{for(const e of s){if(!t.has(e.stateElement))continue;const n=Lf(e.stateElement).get(e.entry.path)===e.entry,o=!0===Bf(e.stateElement).get(e.entry.path)?.includes(e.entry);(n||o)&&Zh(e)}}finally{Uf()}}(e,t,n)}finally{Xf.clear()}}function Qh(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Yh(e,t){if(e.entry.order!==t.entry.order)return e.entry.order-t.entry.order;const n=Math.min(e.indexes.length,t.indexes.length);for(let o=0;o<n;o++)if(e.indexes[o]!==t.indexes[o])return e.indexes[o]-t.indexes[o];return e.indexes.length-t.indexes.length}function Zh(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=Gh(t,n);try{t.createState("writable",e=>{let i;try{i=function(e,t,n){if(0===t.pathInfo.wildcardCount)return e[t.path];return e.$resolve(t.path,n)}(e,n,s)}catch(e){return void Jh(0,n.path,"evaluate",e)}const a=r?function(e,t){return Kf.get(e)?.get(t)}(t,o):Yf(o);r&&Jf(t,o,i),null!==yt&&yt({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){Jh(0,n.path,"handler",e)}}let ep=!1;function tp(){ep||(ep=!0,il("watch",Zf),dl("watch",np),Ks(Xh,10),Gs(Gf))}const np={order:10,register(e,t){var n;n=e,Rf.delete(n),Mf(n),Of.delete(n),function(e){Kf.delete(e)}(e);const o=Ff(e,t);e.setWatchPaths?.(o),null===o&&null==e.scanPaths||e.attachAddressHooks?.("watch",null!==o?F:q)},activate(e,n){t()||null==e.connectedRootNode||(null===n?!0===e.initialized:n===e.connectGeneration)&&Uh(e)},deactivate(e){var t;t=e,Rf.delete(t),Mf(t)}};function op(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(Nu(e.mountPath,o,e.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function sp(e,t,n,o){const s=n[F];if(void 0!==s){const n=[],r=new Set;let i=0;for(const[a,l]of Object.entries(s)){const s=Pu(t,o,a,!1),c=function(e,n,...s){l.call(Nu(t,this,o),e,n,...s)};n.push({path:s,pathInfo:oe(s),handler:c,order:1e6+i++}),r.add(s),e.setPathInfo(s,"prop","watch")}n.length>0&&(!function(e,t){let n=Tf.get(e);void 0===n&&(n=new Map,Tf.set(e,n));for(const e of t){const t=n.get(e.path);void 0===t?n.set(e.path,[e]):t.push(e)}}(e,n),e.addVolumeWatchPaths?.(r),Uh(e))}const r=n[U];if(void 0!==r){const n=new Map;for(const[e,s]of Object.entries(r))n.set(Pu(t,o,e,!1),s);e.mergeVolumeListKeys?.(n)}const i=n[M];"function"==typeof i&&(!function(e,t){let n=ku.get(e);void 0===n&&(n=[],ku.set(e,n)),n.push(t),e.markHasVolume?.()}(e,{mountPath:t,injections:o,callback:i}),e.enableUpdatedCallback?.());for(const e of["$commandTokens","$eventTokens","$on","$errorCallback"])void 0!==n[e]&&console.warn(`[@wcstack/state] volume "${t}" declares ${e}, which volumes do not support. Declare it on the root state instead.`)}function rp(e,t,n,o=[]){!function(e,t,n,o){for(const e of o){const o=e.innerSegments[0],s=Object.getOwnPropertyDescriptor(n,o);void 0===s||"function"!=typeof s.get&&"function"!=typeof s.set&&"function"!=typeof s.value||ee(`Volume "${t}" declares "${o}" as an accessor or a method and also injects it ("${S}.${o}: ${e.outerPathInfo.path}"). Rename one of them.`)}const s=n[F];if(void 0!==s){"object"==typeof s&&null!==s||ee(`${F} must be an object mapping state paths to handler functions.`);for(const[e,t]of Object.entries(s))"function"!=typeof t&&ee(`${F} entry "${e}" must be a function.`),zf(e)}const r=n[U];if(void 0!==r){"object"==typeof r&&null!==r||ee(`${U} must be an object mapping list paths to key specs.`);for(const[n,s]of Object.entries(r)){(0===n.length||"string"!=typeof s&&"function"!=typeof s)&&ee(`${U} entry "${n}" must map a list path to a field name or a key function.`);const r=Pu(t,o,n,!1);e.listKeys?.has(r)&&ee(`${U} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n.$streams&&ee(`Volume "${t}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&ee(`Volume "${t}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[V]&&ee(`Volume "${t}" declares ${V}, which volumes do not support yet. Declare the recursion anchor on the root state — the anchor path is resolved against the root tree.`);for(const e of Object.keys(fc(n)))-1!==e.indexOf(H)&&ee(`Volume "${t}" declares "${e}", which uses "${H}". Volumes do not support recursive getters yet — declare them on the root state.`)}(e,t,n,o);const{data:s,accessors:r}=function(e,t){const n={},o=new Map;for(const[s,r]of Object.entries(Object.getOwnPropertyDescriptors(e)))s.startsWith("$")||t.has(s)||("function"!=typeof r.get&&"function"!=typeof r.set?"function"!=typeof r.value&&(n[s]=r.value):o.set(s,r));return{data:n,accessors:o}}(n,new Set(o.map(e=>e.innerSegments[0]))),i=oe(t),a=!0===e.hydratedFromSsr;e.createState("writable",e=>{if(1===i.segments.length&&t in e){if(a)return;ee(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let t=0;t<i.segments.length-1;t++){const o=i.segments[t],s=""===n?o in e:void 0!==e[n+l+o];n=""===n?o:n+l+o,s||(e[n]={})}if(i.segments.length>1&&void 0!==e[t]){if(a)return;ee(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}e[t]=s}),function(e,t){let n=xu.get(e);void 0===n&&(n=new Set,xu.set(e,n)),n.add(t)}(e,t),e.markHasGraftedVolumes?.();for(const[n,s]of r){const r=t+l+n,i=s.get,a=s.set,c={enumerable:!1,configurable:!0};"function"==typeof i&&(c.get=function(){return i.call(Nu(t,this,o))}),"function"==typeof a&&(c.set=function(e){a.call(Nu(t,this,o),e)}),e.defineTreeAccessor(r,c)}sp(e,t,n,o);const c=n.$connectedCallback;return"function"==typeof c&&e.createState("writable",e=>{let n;try{n=c.call(Nu(t,e,o))}catch(e){return void console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)}n instanceof Promise&&n.catch(e=>{console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)})}),{rootStateElement:e,mountPath:t,volumeState:n,injections:o}}function ip(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=rp(e,t.mountPath,t.volumeState,t.injections)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" failed to graft.`,e)}finally{t.onGrafted(n)}}let ap=!1;function lp(){var e;ap||(ap=!0,Ku||(Ku=!0,il("scopes",Gu)),tf||(tf=!0,cc("scopes",ef)),Pf(),Mu=ip,e=cp,ma.includes(e)||ma.push(e))}function cp(e,t){(function(e){const t=bu.get(e);return void 0!==t&&t.size>0})(e)&&t.markHasVolume?.(),function(e,t){Cu.delete(e);const n=Au.get(e);if(void 0===n||0===n.length||null===Mu)return;Au.delete(e);const o=Mu;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,t)}const dp={name:"scopes",install(){lp(),wu||(wu=!0,cc("dcc",yu))}},up=/^@@wcs-(?:for|if|elseif|else):[^-]/,fp=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,hp=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,pp=/^@@wcs-text-start:(.+)$/;function mp(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class gp extends uc{_stateData=null;_templates=null;_hydrateProps=null;get version(){return this.getAttribute("version")||""}get stateData(){return null===this._stateData&&(this._stateData=this._loadStateData()),this._stateData}get templates(){return null===this._templates&&(this._templates=this._loadTemplates()),this._templates}get hydrateProps(){return null===this._hydrateProps&&(this._hydrateProps=this._loadHydrateProps()),this._hydrateProps}getTemplate(e){return this.templates.get(e)??null}verifyVersion(){const e=this.version;if(!e)return!0;const t=e.split("."),n=Qc.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 find(e){const t=o.tagNames.ssr,n=e instanceof Element?e:e instanceof Document?e.documentElement:null;if(!n)return null;return n.querySelector(t)}static extractStateData(e){const t=e.__state;if(!t||"object"!=typeof t)return{};const n={};for(const e of Object.keys(t)){if(e.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(t,e);if(void 0!==o&&"function"==typeof o.get)continue;const s=t[e];"function"!=typeof s&&(n[e]=s)}return n}static buildContent(e,t){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=mp(JSON.stringify(t)),e.appendChild(n);const s=Array.from($a.keys());for(const t of s){const n=Sa(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(Pi);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],o=Si(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=mp(JSON.stringify(t)),e.appendChild(n)}}Pi.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(fp.test(e.data)||hp.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;up.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=pp.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;fp.test(e.data)&&i.push(e)}for(const e of i){const t=fp.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()}gp.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const e=a.currentNode;if(up.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()}}const yp={protocol:"wcs-ssr-snapshot",version:1,build:function(e){const t=o.tagNames.state,n=o.tagNames.ssr,s=e.querySelectorAll(`${t}[enable-ssr]:not([mount]):not([bind-component])`);for(const e of s){const t=e.previousElementSibling;if(null!==t&&t.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",Qc),gp.buildContent(o,gp.extractStateData(e)),e.parentNode?.insertBefore(o,e)}}};const wp=new Set(["for","if","elseif","else"]);function bp(e){const t=new ls;if(0===e.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:t};const n=e[0].parentNode,o=e[e.length-1].nextSibling,s=document.createElement("div");for(const t of e)s.appendChild(t);const[r,i]=dt(s),a=t.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:t}}function vp(e,t,n){for(const o of t)"event"===o.bindingType||wp.has(o.bindingType)||o.node.nodeType===Node.COMMENT_NODE||o.statePathName in A||oe(o.statePathName).wildcardCount>n||e.push(o)}function $p(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 xp(e,t){const n=e;let s=null;for(const[e,r]of t.templates){let t=Ce(r.getAttribute(o.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&s&&(t={...s,outFilters:[...s.outFilters,Na()],bindingType:"else"}),"if"===i||"elseif"===i?s=t:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?t.statePathName:void 0;Ra(a),"string"==typeof l&&Ma(a,l),Ba(n,a,l);xa(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:Ta(a)})}}const Sp={hydrate:async function(e){await ia(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="${Qc}". Falling back to full render.`),gp.cleanupDom(e),!1}for(const n of t)xp(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=fp.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),s=function(e,t){const n=new Map,o=[];for(const s of t){if(0===s.nodes.length)continue;const t=ti(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a}=bp(s.nodes);Or(t,a);for(const e of i)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");ys(t,r),jr(t,i);const l=[];for(const e of r)e.statePathName in A&&l.push(e);if(vs(t,l),"for"===s.type&&null!==s.index){const i=$p(e,"for",s.uuid);if(i){const e=ks(null,s.index);fi(i,e,t),hi(i,s.nodes[s.nodes.length-1]),Gr(i,t);const l=oe(s.path+"."+c);Lr(t,mn(l,e)),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),vp(o,r,l.wildcardCount);let d=n.get(s.uuid);d||(d=[],n.set(s.uuid,d)),d.push(e)}}else{const n=$p(e,s.type,s.uuid);n&&(Gr(n,t),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),vp(o,r,0))}}for(const[t,o]of n){const n=$p(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=Sa(t);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=ga(s);a&&a.createState("readonly",e=>{const t=e[i];Array.isArray(t)&&Ws(t,o)})}return o}(document.body,n);gp.removeBlockBoundaryComments(document.body);const r=[];for(const e of t)e.parentNode&&(r.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());gp.restoreTextBindings(document.body);const[i,a]=dt(document.body);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||(gt(e,null),t.setAttribute("data-wcs-completed",""))}else gt(e,null);const l=[],d=[],u=cs(document.body).initialize(a);for(const e of u)if("event"!==e.bindingType)if(wp.has(e.bindingType))d.push(e);else{if(e.statePathName.includes(c))continue;l.push(e)}for(const e of d)if("for"===e.bindingType){const t=sn(e),n=ga(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&(vt(t,o),Nt(t,o))})}oa([...l,...s]);for(const{el:e,parent:t,next:n}of r)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},loadState(e){const t=e.parentNode;if(!t)return null;const n=gp.find(t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(e){await ya(e.rootNode);const t=gp.extractStateData(e),n=document.createElement(o.tagNames.ssr);n.setAttribute("version",Qc),gp.buildContent(n,t),e.parentNode?.insertBefore(n,e)}};let Pp=!1;function Ip(){var t;Pp||(Pp=!0,da=Sp,t=e=>{e.get(o.tagNames.ssr)||e.define(o.tagNames.ssr,gp)},yc.includes(t)||yc.push(t),function(){const t=globalThis;void 0===t[e]&&(t[e]=yp)}())}const Np={name:"ssr",install(){Ip()}},kp="[wcs/scan-declaration-invalid]",_p=Object.freeze([]);function Ap(e){return`${q} entry "${e}"`}function Cp(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function Ep(e,t,n,o){return`[wcs/scan-source-computed] ${e} ${t} "${n}" ${o===n?"is a getter":o.includes(`${c}${c}`)?`is computed by the recursive getter "${o}"`:`is under the getter "${o}"`}. A getter re-evaluates whenever its inputs change, so folding it would count re-evaluations, not events. Fold the plain value the getter reads, or use "on" with an event token.${ae}`}function Mp(e,t,n){0===n.length&&ee(`${kp} ${e} "${t}" must be a non-empty state path.${ae}`),n.startsWith("$")&&ee(`${kp} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${ae}`),n.includes("@")&&ee(`${kp} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${ae}`),n in Object.prototype&&ee(`${kp} ${e} ${t} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ae}`);const o=oe(n);for(const s of o.segments)0===s.length&&ee(`${kp} ${e} ${t} "${n}" has an empty path segment.${ae}`);return o.wildcardCount>d&&ee(`${kp} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function Op(e,t,n,o){const s=Ap(e);0===e.length&&ee(`${kp} ${q} entry name must be a non-empty string.${ae}`),(e.includes(l)||e.includes(c))&&ee(`${kp} ${s} must be a flat property name ("${l}" and "${c}" are not allowed). The output is a property the runtime owns.${ae}`),e.startsWith("$")&&ee(`${kp} ${s} must not start with "$" (reserved namespace).${ae}`),e in Object.prototype&&ee(`${kp} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ae}`),t.has(e)&&ee(`${kp} ${s} conflicts with a getter declared on the state.${ae}`),n.has(e)&&ee(`${kp} ${s} conflicts with a setter declared on the state.${ae}`),o.has(e)&&ee(`${kp} ${s} conflicts with the ${z} entry of the same name — each output has exactly one owner.${ae}`)}function Tp(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!function(e,t){return"function"==typeof t&&!0===Nh.get(t)?.has(e)}(e,o)&&ee(`${kp} ${Ap(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${ae}`)}function Rp(e,t,n,o,s,r){const i=Ap(e),a=void 0!==t.from,c=void 0!==t.on;if(a===c&&ee(`${kp} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${ae}`),c){const e=t.on;return"string"==typeof e&&0!==e.length||ee(`${kp} ${i} "on" must be a non-empty event-token name.${ae}`),n.has(e)||ee(`${kp} ${i} on "${e}" is not declared in ${D}.${ie(e,n)}${ae}`),{kind:"event",tokenName:e}}const d=t.from;"string"!=typeof d&&ee(`${kp} ${i} "from" must be a state path string.${ae}`);const u=Mp(i,"from",d),f=Cp(u,o)??r?.recursiveGetterOwning(d)??null;null!==f&&ee(Ep(i,"from",d,f));const h=Cp(u,s);return null!==h&&ee(function(e,t,n){return`${kp} ${e} from "${t}" ${n===t?"is a setter without a getter":`is under the setter without a getter "${n}"`}, so it always reads undefined and every fold would receive undefined. Fold the plain value the setter writes, or use "on" with an event token.${ae}`}(i,d,h)),(d===e||d.startsWith(e+l))&&ee(`${kp} ${i} from "${d}" reads the entry's own output — the scan would fold its own writes forever.${ae}`),{kind:"path",path:d,pathInfo:u}}function jp(e,t,n,o){if(void 0===t)return _p;const s=Ap(e);Array.isArray(t)||ee(`${kp} ${s} "resetOn" must be an array of state paths.${ae}`);const r=[];for(const e of t){"string"!=typeof e&&ee(`${kp} ${s} "resetOn" must contain only state path strings.${ae}`);const t=Mp(s,"resetOn",e);t.wildcardCount>0&&ee(`${kp} ${s} resetOn "${e}" must not contain "${c}" — a reset returns the whole output to "initial".${ae}`);const i=Cp(t,o);null!==i&&ee(Ep(s,"resetOn",e,i)),"path"===n.kind&&e===n.path&&ee(`${kp} ${s} resetOn "${e}" is the entry's own "from" — every change would reset instead of fold.${ae}`),"path"===n.kind&&e.startsWith(n.path+l)&&ee(`${kp} ${s} resetOn "${e}" sits under the entry's own "from" "${n.path}" — every write of "from" also lands it, so the reset would win every time and nothing would fold.${ae}`),r.push(e)}return r}function Lp(e,t,n=null){const o=e[q];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&ee(`${kp} ${q} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${ae}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[t,n]of Object.entries(fc(e)))"function"==typeof n.get?s.add(t):"function"==typeof n.set&&i.add(t),"function"==typeof n.set&&r.add(t),"function"==typeof n.value&&a.set(t,n.value);const l=function(e){const t=e[z];return"object"!=typeof t||null===t?new Set:new Set(Object.keys(t))}(e),c=[];let d=0;for(const[e,u]of Object.entries(o)){Op(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&ee(`${kp} ${Ap(e)} must be an object ({ from | on, initial, fold, resetOn? }).${ae}`);const o=u;Tp(e,a,o);const f=Rp(e,o,t,s,i,n);"initial"in o||ee(`${kp} ${Ap(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${ae}`),"function"!=typeof o.fold&&ee(`${kp} ${Ap(e)} fold must be a function.${ae}`);const h=jp(e,o.resetOn,f,s);c.push({name:e,source:f,fold:o.fold,initial:o.initial,resetOn:h,order:d++})}return function(e){const t=new Set(e.map(e=>e.name)),n=new Map;for(const o of e){for(const e of o.resetOn){const n=oe(e).segments[0];t.has(n)&&ee(`${kp} ${Ap(o.name)} resetOn "${e}" reads the ${q} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${ae}`)}if("path"===o.source.kind){const e=o.source.pathInfo.segments[0];t.has(e)&&n.set(o.name,e)}}for(const e of n.keys()){const o=[e];let s=n.get(e);for(;void 0!==s&&o.length<=t.size;)s===e&&ee(`${kp} ${q} entries ${[...o,e].map(e=>`"${e}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${ae}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}function Wp(e){const t=e.fold;return(n,o,...s)=>{const r=n;let i="read-output";try{const n=r[e.name];i="threw";const a=function(e){return hh.has(e)}(e),l=a&&!Ih(n,e.initial)?Sh(e.initial):n,c=t(l,o,...s);if(Mh(c))return void Oh(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,kh(e.name,c)),a&&wh(e)}catch(t){Eh(e.name,t,i)}}}function Dp(e,t,n){const o=function(e,t){Ef(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&Af(n,e.source.path,e);for(const t of e.resetOn)Af(o,t,e),"event"===e.source.kind&&Af(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return If.set(e,r),r}(e,t);for(const o of t){const t=n.get(o.name);"event"===o.source.kind&&void 0!==t&&(o.resetOn.some(n=>t.includes(n)&&Ys().hasQueuedPath(e,n))&&yh(o))}const s=new Set;for(const t of o.byFromPath.keys())s.add(t),e.setPathInfo(t,"prop","scan");for(const t of o.byResetPath.keys())e.setPathInfo(t,"prop","scan");return s.size>0?s:null}const Bp="scanEntries",zp={order:8,validate(e,t,n){const o=Lp(t,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Bp,o)},applyEarly(e,t,n){const o=n.get(Bp)??null;null!==o&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=Sh(n.initial);e[n.name]=t,kh(n.name,t)}}(t,o),function(e,t){for(const n of t)"event"===n.source.kind&&Cn(e,n.source.tokenName).subscribe(Wp(n))}(e,o))},register(e,t,n){const o=n.get(Bp)??null,s=function(e){const t=new Map,n=Cf(e);if(void 0!==n)for(const e of n.entries)wh(e)&&t.set(e.name,e.resetOn);return Ef(e),t}(e);e.setScanPaths?.(null===o?null:Dp(e,o,s))}};let Fp=!1;const qp=Object.freeze([]),Vp=Object.freeze([]);function Hp(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??qp,i=e.dynamicDependency.get(n)??qp,a=t.byFromPath.get(n)??Vp;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}const Up=(e,t)=>t,Gp=new Set;function Kp(e,t){const n=t[z];if(void 0===n)return void lh(e,Gp);"object"==typeof n&&null!==n||ee(`${z} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[s,r]of Object.entries(n)){0===s.length&&ee(`${z} entry name must be a non-empty string.`),s.includes(l)&&ee(`${z} entry "${s}" must be a flat property name ("${l}" is not allowed).`),s.includes(c)&&ee(`${z} entry "${s}" must be a flat property name ("${c}" is not allowed).`),s.startsWith("$")&&ee(`${z} entry "${s}" must not start with "$" (reserved namespace).`),s in Object.prototype&&ee(`${z} entry "${s}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(s)&&ee(`${z} entry "${s}" conflicts with a getter declared on the state.`),e.setterPaths.has(s)&&ee(`${z} entry "${s}" conflicts with a setter declared on the state.`),"object"==typeof r&&null!==r||ee(`${z} entry "${s}" must be an object ({ args?, source, fold?, initial? }).`);const n=r;"function"!=typeof n.source&&ee(`${z} entry "${s}" source must be a function.`);const i=void 0!==n.fold;i&&"function"!=typeof n.fold&&ee(`${z} entry "${s}" fold must be a function.`),i&&!("initial"in n)&&ee(`${z} entry "${s}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&ee(`${z} entry "${s}" args must be a function.`);const a={name:s,definition:{args:n.args??null,source:n.source,fold:n.fold??Up,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};s in t||(t[s]=a.definition.initial),o.set(s,a)}!function(e,t){dh.set(e,t)}(e,o),lh(e,new Set(o.keys()))}const Jp=new WeakMap,Xp=new WeakMap;function Qp(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=uh(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&uh(e).has(n),ownKeys:()=>Array.from(uh(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=uh(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){ee(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){ee(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function Yp(e){const t=Jp.get(e);if(void 0!==t)return t;const n=Qp(e,G,e=>e.status);return Jp.set(e,n),n}function Zp(e){const t=Xp.get(e);if(void 0!==t)return t;const n=Qp(e,K,e=>e.error);return Xp.set(e,n),n}function em(e){Jp.delete(e),Xp.delete(e)}let tm=null;function nm(e,t){let n=e;for(let e=1;e<t.length;e++){if(Object(n)!==n)return;n=Reflect.get(n,t[e])}return n}const om={read(e,t){!function(e,t){null!==tm&&tm.add(Ht(e,t))}(e,t);const n=t.pathInfo.segments[0];return n===G?nm(Yp(e),t.pathInfo.segments):n===K?nm(Zp(e),t.pathInfo.segments):ol},get:(e,t)=>t===G?Yp(e.stateElement):t===K?Zp(e.stateElement):ol};async function sm(e,t,n,o){let s=null,r=null;const i=()=>{if(s&&s!==r){r=s;try{s.return?.()?.then?.(void 0,()=>{})}catch{}}};n.addEventListener("abort",i,{once:!0});try{const r=await e(t,n);if(s=function(e,t){if("function"==typeof e?.getReader)return async function*(e,t){const n=e.getReader(),o=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",o,{once:!0});try{for(;;){const{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t.removeEventListener("abort",o),n.releaseLock()}}(e,t);if("function"==typeof e?.[Symbol.asyncIterator])return e;throw new TypeError("[@wcstack/state] $streams: source must return an AsyncIterable or a ReadableStream (got neither).")}(r,n)[Symbol.asyncIterator](),n.aborted)return void i();for(;;){const e=await s.next();if(e.done)break;if(n.aborted)return;o.fold(e.value)}if(n.aborted)return;o.done()}catch(e){if(n.aborted)return;o.fail(e)}finally{n.removeEventListener("abort",i)}}function rm(e){fm();const t=uh(e);if(0!==t.size){!function(e){oh.add(e)}(e);for(const n of t.values())im(e,n)}}function im(e,t){t.controller?.abort();const n=new AbortController;t.controller=n;const o=function(e,t){const n=t.definition.args;if(null===n)return void t.depAddresses.clear();const o=tm,s=new Set;let r;tm=s;try{e.createState("readonly",e=>{r=n(e)})}finally{tm=o}r instanceof Promise&&ee(`${z} entry "${t.name}" args must be synchronous (it returned a Promise).`);const i=`${G}${l}${t.name}`,a=`${K}${l}${t.name}`;for(const n of s){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==e||o.path!==t.name&&o.path!==i&&o.path!==a||ee(`${z} entry "${t.name}" args must not read the stream itself ("${o.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),o.wildcardCount>0&&ee(`${z} entry "${t.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return t.depAddresses=s,r}(e,t);!function(e,t){const n=Cf(e);if(void 0!==n&&0!==t.depAddresses.size)for(const o of n.entries){if("path"!==o.source.kind||o.source.pathInfo.segments[0]!==t.name)continue;const s=Hp(e,n,o.name);for(const e of t.depAddresses){const n=e.absolutePathInfo.pathInfo.path;s.has(n)&&ee(`[wcs/scan-feedback-loop] ${z} entry "${t.name}" args read "${n}", which is derived from the ${q} output "${o.name}" that this stream feeds. Every landing would restart the stream on its own result. Advance the cursor from an event ($on) and keep it a plain property instead of deriving it from the accumulator.`)}}}(e,t),e.createState("writable",e=>{e[t.name]=t.definition.initial}),am(e,t,"active",null);const s=t.definition,r={fold(n){e.createState("writable",e=>{e[t.name]=s.fold(e[t.name],n)})},done(){am(e,t,"done",null)},fail(o){am(e,t,"error",o),n.abort()}};sm(s.source,o,n.signal,r)}function am(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return ah.get(e)?.get(t)??{status:"idle",error:null}}(e,t.name),r=s.status!==n,i=!Object.is(s.error,o);(r||i)&&(!function(e,t,n,o){let s=ah.get(e);void 0===s&&(s=new Map,ah.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{r&&e.$postUpdate(`${G}${l}${t.name}`),i&&e.$postUpdate(`${K}${l}${t.name}`)}))}function lm(e){const t=rh();if(0===t.size)return;const n=[];for(const o of t)for(const t of uh(o).values())for(const s of t.depAddresses)if(e.has(s)){n.push({stateElement:o,entry:t});break}for(const{stateElement:e,entry:o}of n)if(t.has(e)&&uh(e).get(o.name)===o)try{im(e,o)}catch(n){o.controller?.abort(),t.has(e)&&uh(e).get(o.name)===o&&am(e,o,"error",n)}}let cm=!1;const dm=new WeakMap,um={order:20,apply(e,t){var n;em(e),fh(n=e),sh(n),dh.delete(n),Kp(e,t),void 0!==t[z]&&e.attachAddressHooks?.("streams",z)},activate(e,n){if(!t()&&null!=e.connectedRootNode){if(null===n){if(!0!==e.initialized)return;return rm(e),void dm.set(e,e.connectGeneration??0)}n===e.connectGeneration&&dm.get(e)!==n&&rm(e)}},deactivate(e){fh(e),em(e)}};function fm(){cm||(cm=!0,il("streams",om),dl("streams",um),Ks(lm,20))}const hm=[Ed,{name:"temporal",install(){tp(),Fp||(Fp=!0,dl("scan",zp),Gs(gh)),fm()}},ru,dp,Np,cd,vd];await function(e,t){!function(e){for(let t=0;t<e.length;t++)e[t].install()}(hm),vc(e,t)}();
1
+ const e=Symbol.for("wcstack.ssr.snapshotBuilder");function t(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const n={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,enableDirectionalInitialSync:!0,enablePropagationContext:!0,enableContractAnalyzer:!1,sameValueGuard:!0},o=n;const s=Symbol.for("wcstack.binder");const r=Symbol.for("wcstack.binder.pending"),i=Symbol.for("wcstack.binder.taken");function a(){const e=function(){const e=globalThis[s];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}();if(null===e)return;const t=function(){const e=globalThis;let t=e[r];return void 0===t&&(t=[],e[r]=t),t}();if(0===t.length)return;const n=t.splice(0,t.length),o=function(){const e=globalThis;let t=e[i];return void 0===t&&(t=new WeakSet,e[i]=t),t}();for(const t of n)o.add(t),e.bind(t)}const l=".",c="*",d=128,u=128,f="#",h="|",p="prevent",g="stop",m="ro",y="init",w="sync",b="else",v="...",$="on",x="eventToken",S="state",P="command",I="class",k="attr",N="style",_={};for(let e=0;e<d;e++)_[`$${e+1}`]=e;const A=Object.freeze(_),C="$connectedCallback",E="$disconnectedCallback",M="$renderedCallback",O="$errorCallback",T="$stateReadyCallback",R="$bindables",j="$commands",L="$commandTokens",W="$command",D="$eventTokens",B="$on",z="$stream",F="$watch",q="$scan",V="$recursion",H="**",K="$listKeys",U="$streamStatus",G="$streamError",J="data-wc-definition",X=/\{\{\s*(.+?)\s*\}\}/g,Q=new Set(["SCRIPT","STYLE"]);function Y(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&&Q.has(e.parentElement.tagName)||Z(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),Y(t.content)}else Y(e.content)}function Z(e){const t=e.data;if(X.lastIndex=0,!X.test(t))return;X.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=X.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)}function ee(e){throw new Error(`[@wcstack/state] ${e}`)}const te=new Map;let ne=0;function oe(e){let t=te.get(e);if(void 0!==t)return t;-1!==e.indexOf(H)&&ee(`[wcs/recursion-unsupported] "${e}" uses "${H}", which is not accepted here. It is only meaningful in a $recursion declaration, in a recursive getter key, and in the path argument of $getAll / $setAll — and only when the state declares a $recursion anchor.`);const n=function(e){let t=1;for(let n=0;n<e.length;n++)e[n]===l&&t++;return t}(e);return n>512&&ee(`[wcs/binding-syntax] "${e}" has ${n} path segments — the limit is 512. Every prefix of a path is interned, so the cost grows with the square of the depth.`),t=Object.freeze(new se(e)),te.set(e,t),t}class se{id=++ne;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:oe(t),n=e.split("."),o=[],s=[],r=[],i={},a=[],l=[],d=[],u=[];let f="",h="",p=0;for(let e=0;e<n.length;e++)f+=n[e],n[e]===c&&(r.push(f),i[f]=p,a.push(t(f)),l.push(h),d.push(t(h)),u.push(e),p++),o.push(f),s.push(t(f)),h=f,f+=".";const g=r.length>0?r[r.length-1]:null,m=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=d,this.wildcardParentPathInfoSet=new Set(d),this.wildcardPositions=u,this.lastWildcardPath=g,this.lastWildcardInfo=g?t(g):null,this.parentPath=m,this.parentPathInfo=m?t(m):null,this.wildcardCount=p}}function re(e,t,n){if(Math.abs(e.length-t.length)>n)return n+1;const o=new Array(t.length+1),s=new Array(t.length+1);for(let e=0;e<=t.length;e++)o[e]=e;for(let n=1;n<=e.length;n++){s[0]=n;for(let r=1;r<=t.length;r++){const i=e[n-1]===t[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let e=0;e<=t.length;e++)o[e]=s[e]}return o[t.length]}function ie(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=re(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const ae=" Validate statically: npx @wcstack/lint <file>.",le=new Set(["if","elseif","else","for"]);function ce(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}function de(e){if(0===e.length)return"";let t="";for(let n=0;n<e.length;n++){const o=e[n];n>0&&(t+="|"),t+=`${o.filterName}(${ce(o.args,o.literals??o.args)})`}return t}const ue=new Map([["not",()=>e=>!e]]),fe=new Map([["not",[0,0]]]),he={input:new Map,output:new Map},pe={input:new Map,output:new Map},ge={input:new Map,output:new Map},me=new Map;function ye(e,t,n,o){const s=he[e],r=pe[e];for(const e of Object.keys(t)){s.set(e,t[e]);const o=n?.[e];void 0===o?r.delete(e):r.set(e,o)}const i=o??{},a=ge[e];for(const[e,n]of[...a])Object.prototype.hasOwnProperty.call(t,n)&&i[e]!==n&&a.delete(e);for(const e of Object.keys(i))a.set(e,i[e]);me.clear()}function we(e,t,n,o=t){const s=ge[n].get(e)??e,r=`${s}${ce(t,o)}:${n}`,i=me.get(r);if(void 0!==i)return i;const a=he[n].get(s)??ue.get(s);if(void 0===a){const t=0===he[n].size?' No formatting filters are installed — add them with installFeatures([...]) from "@wcstack/state/features/formats".':"";ee(`[wcs/filter-unknown] filter not found: ${e}.${ie(e,function(e){return[...new Set([...ue.keys(),...he[e].keys()])]}(n))}${t}${ae}`)}const l=pe[n].get(s)??fe.get(s);void 0!==l&&(t.length<l[0]||t.length>l[1])&&ee(t.length<l[0]?`[wcs/filter-arity] filter "${e}" requires at least ${l[0]} argument(s) (${t.length} given).${ae}`:`[wcs/filter-arity] filter "${e}" accepts at most ${l[1]} argument(s) (${t.length} given).${ae}`);const c=a(t,o);return me.set(r,c),c}function be(e,t,n){const o=-1===t?e.length:t;let s=0;for(;s<o&&/\s/.test(e[s]);)s++;const r=-1===n?0:n;let i=e.length;for(;i>r&&/\s/.test(e[i-1]);)i--;return e.slice(s,i)}const ve=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function $e(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:ve.test(e)?Number(e):e)}function xe(e){const t=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const e=be(o,i,a);t.push(e),n.push($e(e,r)),o="",r=!1,i=-1,a=-1};for(let t=0;t<e.length;t++){const n=e[t];s?n===s?s=null:(-1===i&&(i=o.length),o+=n,a=o.length):'"'===n||"'"===n?(s=n,r=!0):","===n?l():o+=n}null!==s&&ee(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${e})". Close the quote.${ae}`);const c=be(o,i,a);return(c||r)&&(t.push(c),n.push($e(c,r))),{args:t,literals:n}}const Se=e=>e.trim(),Pe=e=>"'"===e||'"'===e;function Ie(e,t){let n=null;for(let o=0;o<e.length;o++){const s=e[o];if(null!==n)s===n&&(n=null);else if(Pe(s))n=s;else if(s===t)return o}return-1}function ke(e,t){const n=[];let o=null,s=0;for(let r=0;r<e.length;r++){const i=e[r];null!==o?i===o&&(o=null):Pe(i)?o=i:i===t&&(n.push(e.slice(s,r)),s=r+1)}return n.push(e.slice(s)),n}function Ne(e,t,n){const o=n??e.join("|");return e.map(e=>{const n=Ie(e,"(");let s=function(e,t){let n=null,o=-1;for(let s=0;s<e.length;s++){const r=e[s];null!==n?r===n&&(n=null):Pe(r)?n=r:r===t&&(o=s)}return o}(e,")");if(-1===s&&(s=e.lastIndexOf(")")),-1!==n&&-1===s&&ee(`[wcs/binding-syntax] Invalid filter format: missing closing parenthesis in "${e}".${ae}`),-1!==s&&-1===n&&ee(`[wcs/binding-syntax] Invalid filter format: missing opening parenthesis in "${e}".${ae}`),-1!==s&&s<n&&ee(`[wcs/binding-syntax] Invalid filter format: ")" comes before "(" in "${e}".${ae}`),-1!==s&&e.slice(s+1).trim().length>0){const t=e.slice(s+1).trim();ee(`[wcs/binding-syntax] "${e}": unexpected "${t}" after the filter's closing ")" — separate filters with "|" (write "${e.slice(0,s+1)}|${t}").${ae}`)}const r=(-1===n?e:e.substring(0,n)).trim();if(0===r.length&&ee(`[wcs/binding-syntax] an empty filter in "${o}" — remove the extra "|" or name the filter.${ae}`),r.includes(f)){const[e,n]=r.split(f);ee("input"===t?`[wcs/binding-syntax] "${r}" is not a filter name: a modifier list "${f}${n}" comes before the input filters, not inside one — write "<property>${f}${n}|${e}".${ae}`:`[wcs/binding-syntax] "${r}" is not a filter name: "${f}" cannot appear in one. Modifiers belong on the left side of the binding, before the ":" — write "${e}" here.${ae}`)}if(-1===n)return{filterName:r,args:[],literals:[]};return{filterName:r,...xe(e.substring(n+1,s))}})}const _e=new Map;function Ae(e){const t=Ie(e,h);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),_e.has(s)?r=_e.get(s):(o=ke(s,h).map(Se),r=Ne(o,"input",e),_e.set(s,r))):n=e.trim();const i=n.split(f).map(Se);i.length>2&&ee(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${f}" — write "${i[0]}${f}${i.slice(1).join(",")}".${ae}`);const[a,c]=i,d=a.split(l).map(Se);d.length>1&&""===d[0]||0!==a.length&&!d.some(e=>0===e.length)||ee(`[wcs/binding-syntax] "${e}": the left side of a binding must name a property — write "<property>: <path>" (modifiers and input filters come after the name).${ae}`);return{propName:a,propSegments:d,propModifiers:c?c.split(",").map(Se):[],inFilters:r}}const Ce=new Map;function Ee(e){const t=Ie(e,h);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Ce.has(s)?r=Ce.get(s):(o=ke(s,h).map(Se),r=Ne(o,"output",e),Ce.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&ee(`"${n}": the "@name" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount="...">) and read it by its path prefix instead.`);const i=n,a=i.startsWith(l),c=a?i.slice(1):i;(c.length>0&&c.split(l).some(e=>0===e.length)||!a&&0===c.length)&&ee(`[wcs/binding-syntax] "${e}": the right side of a binding must name a state path — write "<property>: <path>" (a path segment cannot be empty; "." alone and a leading "." are the loop-relative shorthand).${ae}`);return{statePathName:i,statePathInfo:oe(i),outFilters:r}}const Me=new Set([b,"if","elseif","for",v]),Oe=new Set([I,k,N,P,x,S]);function Te(e){const[...t]=function(e){return ke(e,";")}(e).map(Se).filter(e=>e.length>0),n=t.map(e=>{const t=Ie(e,":");-1===t&&ee(`[wcs/binding-syntax] Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.${ae}`);const n=e.slice(0,t).trim(),o=e.slice(t+1).trim(),s=n.split(f)[0].split(h)[0].trim();if(s!==n&&Me.has(s)&&ee(`[wcs/binding-syntax] "${e}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${ae}`),n===b){o.length>0&&ee(`[wcs/binding-syntax] "${e}": "else" takes no value — write "else:".${ae}`);const t=oe("#else");return{propName:b,propSegments:[b],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===v){0===o.length&&ee(`[wcs/binding-syntax] Invalid spread binding "${e}": spread target path is required.${ae}`);const t=Ee(o);return t.outFilters.length>0&&ee(`[wcs/binding-syntax] Invalid spread binding "${e}": filters are not allowed on spread targets.${ae}`),{propName:v,propSegments:[v],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Ee(o),bindingType:n}}if("radio"===s||"checkbox"===s){const e=Ee(o);return{...Ae(n),...e,bindingType:s}}{const e=Ee(o),t=Ae(n);if(""===t.propSegments[0]&&t.propSegments.length>1){const o=t.propSegments.slice(1);return(o.includes("")||Oe.has(o[0]))&&ee(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...Oe].join(", ")}).${ae}`),{...t,propName:o.join(l),propSegments:o,...e,bindingType:"prop"}}return t.propSegments[0]===x||t.propSegments[0].startsWith($)?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>le.has(e.bindingType))&&ee(`[wcs/template-syntax] Invalid bindText: "${e}". 'if', 'elseif', 'else', and 'for' bindings must be single binding. Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).${ae}`)}return n}const Re=new WeakMap,je=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Le=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function We(e){const t=Re.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),s=Le.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return je.has(r)?(Re.set(e,s[2]),s[2]):null}function De(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Ee(e),bindingType:"text"}}const Be=new WeakMap,ze=new WeakSet;let Fe=0;async function qe(e){const t=function(e){let t,n=Be.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++Fe,promise:o,resolve:t},Be.set(e,n),ze.has(e)&&n.resolve(),n}(e);await t.promise}function Ve(e){const t=Be.get(e);void 0===t?ze.add(e):t.resolve()}const He=new WeakMap;function Ke(e){const t=He.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{He.set(e,n)}}function Ue(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function Ge(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return Ue(t);if(void 0!==n)return Ue(n)}return Ue(globalThis.customElements)}function Je(e,t){e.upgrade?.(t)}function Xe(e){try{if(null===e||"object"!=typeof e&&"function"!=typeof e)return null;const t=e,n=t.addEventListener,o=t.removeEventListener,s=t.constructor?.wcBindable;if("function"!=typeof n||"function"!=typeof o)return null;if("wc-bindable"!==s?.protocol)return null;if(!Number.isInteger(s.version)||s.version<1)return null;const r=et(s.properties,Qe);if(null===r)return null;const i=void 0===s.inputs?new Map:et(s.inputs,Ye);if(null===i)return null;const a=void 0===s.commands?new Map:et(s.commands,Ze);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Qe(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&("string"==typeof t.event&&0!==t.event.length&&(void 0===t.getter||"function"==typeof t.getter))}function Ye(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.attribute||"string"==typeof t.attribute)}function Ze(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.async||"boolean"==typeof t.async)}function et(e,t){if(!Array.isArray(e))return null;const n=new Map;for(const o of e){if(!t(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function tt(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:oe(n),inFilters:[],outFilters:[],bindingType:"prop"}}function nt(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function ot(e,t,n={}){const s=n.allowDeferred??!0;if(!t.some(e=>"spread"===e.bindingType))return t;const r=[],i=new WeakSet;for(const n of t){if("spread"!==n.bindingType){r.push(n);continue}e.nodeType!==Node.ELEMENT_NODE&&ee("Spread binding requires an element node.");const t=e,o=Ke(t);null===o&&ee(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=Ge(t);null===a&&ee(`CustomElementRegistry is unavailable for <${o}>.`);if(void 0===a.get(o)){s||ee(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Je(a,t);const l=Xe(t);null===l&&ee(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=new Set;for(const e of l.knownProperties.keys()){if(d.has(e))continue;d.add(e);const t=tt(e,c);i.add(t),r.push(t)}for(const e of l.declaredInputs.keys()){if(d.has(e))continue;d.add(e);const t=tt(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=nt(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=nt(r[t]);if(null!==n){if(a.get(n)===t)l.push(r[t]);else if(o.debug&&i.has(r[t])){const o=r[a.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 l.push(r[t])}return l}function st(e,t){let n=e;for(let e=0;e<t.length;e++){let o=t[e];for(n=n.firstChild;null!==n&&o>0;)n=n.nextSibling,o--;if(null===n)break}return n}function rt(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o],r=s.literals??s.args;n.push({filterName:s.filterName,args:s.args,literals:r,filterFn:we(s.filterName,s.args,t,r)})}return n}function it(e){return{...e,inFilters:rt(e.inFilters,"input"),outFilters:rt(e.outFilters,"output")}}const at=new WeakMap;function lt(e){return at.get(e)||null}function ct(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(o.bindAttributeName)}function dt(e){const t=[],n=e.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!ct(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function ut(e,t){for(let n=0;n<t.length;n++){const o=t[n];if(o!==e&&o.contains(e))return!0}return!1}function ft(e){const t=[],n=dt(e),s=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!==We(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const e=s.currentNode;n.length>0&&ut(e,n)||t.push(e)}return t}const ht=new WeakSet;function pt(e,t,n,o){const s=ot(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?Ke(e):null;return null===n&&ee("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}ht.add(e);const r=function(e,t){const n=[];for(const o of t){const t=rt(o.inFilters,"input"),s=rt(o.outFilters,"output");if("text"!==o.bindingType)n.push({...o,inFilters:t,outFilters:s,node:e,replaceNode:e});else{const r=e.nodeType===Node.TEXT_NODE?e:document.createTextNode("");n.push({...o,inFilters:t,outFilters:s,node:e,replaceNode:r})}}return n}(e,function(e,t){return void 0===t?e:e.map(e=>null!=e.uuid?e:t(e))}(s,o));return function(e,t){at.set(e,t)}(e,r),Ve(e),{bindings:r,deferred:null}}function gt(e,t){const n=ft(e),o=[],s=[];for(const e of n){if(ht.has(e))continue;const n=pt(e,Fa(e),{allowDeferred:!0},t);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function mt(e){ht.add(e)}function yt(e){const{node:t,parseResults:n,transform:o}=e;!function(e){ht.delete(e)}(t);return pt(t,n,{allowDeferred:!1},o).bindings}const wt=new WeakMap;let bt=null;function vt(e){let t=e;for(;t;){const e=wt.get(t);if(e)return e;let n=t.parentNode;null===n&&null!==bt&&t instanceof ShadowRoot&&(n=bt(t)),t=n}return null}function $t(e,t){null!==t?wt.set(e,t):wt.delete(e)}let xt=null;const St=new WeakMap;function Pt(e){return St.get(e)??[]}function It(e,t){St.set(e,t)}function kt(e){return St.has(e)}const Nt=new WeakMap;let _t=null,At=0;function Ct(e){return Nt.get(e)??[]}function Et(e,t){null===_t?Nt.set(e,t):_t.set(e,t)}function Mt(){At++,null===_t&&(_t=new Map)}function Ot(){if(0!==At&&(At--,!(At>0||null===_t))){for(const[e,t]of _t)Nt.set(e,t);_t=null}}function Tt(e){return(_t?.has(e)??!1)||Nt.has(e)}const Rt=Symbol("$$setLoopContext"),jt=Symbol("$$getByAddress"),Lt=Symbol("$$hasByAddress"),Wt=Symbol("$$connectedCallback"),Dt=Symbol("$$disconnectedCallback"),Bt=Symbol("$$updatedCallback"),zt=Symbol("$$errorCallback"),Ft=new WeakMap,qt=new WeakMap;class Vt{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function Ht(e,t){if(null===t){let t=qt.get(e);return void 0!==t||(t=new Vt(e,null),qt.set(e,t)),t}{let n=Ft.get(t);void 0===n&&(n=new WeakMap,Ft.set(t,n));let o=n.get(e);return void 0!==o||(o=new Vt(e,t),n.set(e,o)),o}}const Kt=new WeakMap;function Ut(e,t){let n=Kt.get(e);void 0===n&&(n=new Map,Kt.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new Gt(e,t)),n.set(t,o)),o}class Gt{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function Jt(e,t){return Ht(Ut(e,t.pathInfo),t.listIndex)}function Xt(e,t,n){return Ht(Ut(e,t),n)}const Qt=new WeakMap;function Yt(e,t){null===t?Qt.delete(e):Qt.set(e,t)}function Zt(e){return Qt.get(e)||null}const en=new Map;function tn(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=en.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,en.set(s,r),r}function nn(e,t,n){return t<0||t>=n?null:e.at(t-n)}function on(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const sn=new WeakMap;function rn(e){const t=vt(e.node);if(null===t)return null;let n=sn.get(t);if(void 0===n)n=new WeakMap,sn.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=tn(t.pathInfo,e.statePathInfo);return n>0&&(o=nn(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const an=new WeakMap;function ln(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=Zt(n);null===t?ee(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function cn(e,t){let n=null;if(n=an.get(e)||null,null!==n)return n;const o=ln(e,t),s=rn(e),r=Ta(o);return null===r&&ee("No state tree found on this root for binding."),n=Xt(r,e.statePathInfo,s),an.set(e,n),n}function dn(e){an.delete(e)}const un=new WeakMap;function fn(e,t){const n=un.get(e);void 0===n?un.set(e,t):n instanceof Set?n.add(t):n!==t&&un.set(e,new Set([n,t])),null!==xt&&xt({type:"state:binding-added",absoluteAddress:e,binding:t})}function hn(e,t){const n=un.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&un.delete(e),null!==xt&&xt({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const pn=new WeakMap;function gn(e){const t=un.get(e);return void 0!==t?t:null!==e.listIndex?pn.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const mn=new WeakMap,yn=new WeakMap;class wn{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]===c?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=bn(e,t)}}function bn(e,t){if(null===t){let t=yn.get(e);return void 0!==t||(t=new wn(e,null),yn.set(e,t)),t}{let n=mn.get(t);void 0===n&&(n=new WeakMap,mn.set(t,n));let o=n.get(e);return void 0!==o||(o=new wn(e,t),n.set(e,o)),o}}const vn=new WeakMap;function $n(e){let t=null;if(t=vn.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=rn(e);null===n&&ee(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=bn(e.statePathInfo,n)}else t=bn(e.statePathInfo,null);return vn.set(e,t),t}function xn(e){vn.delete(e)}function Sn(){const e=new Map,t=new Map;return{add(n,o){let s=e.get(n);return void 0===s&&(s=new WeakSet,e.set(n,s)),!s.has(o)&&(s.add(o),t.set(n,(t.get(n)??0)+1),!0)},remove(n,o){const s=e.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(t.get(n)??1)-1;return r<=0?(e.delete(n),t.delete(n),!0):(t.set(n,r),!1)},has:(t,n)=>e.get(t)?.has(n)??!1,countOf:e=>t.get(e)??0,get keyCount(){return t.size},clear(){e.clear(),t.clear()}}}const Pn=new Map,In=Sn();function kn(e,t){const n=de(e.inFilters);return`${e.statePathName}::${t}::${n}`}function Nn(e){let t="input";for(const n of e.propModifiers)n.startsWith($)&&(t=n.slice(2));return t}function _n(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(m)){const o=Nn(e),s=kn(e,o);let r=Pn.get(s);return void 0===r&&(t=e.statePathName,n=e.inFilters,r=e=>{const o=e.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("checkbox"!==o.type)return void console.warn("[@wcstack/state] event.target is not a checkbox input element.");const s=o.checked;let r=o.value;for(const e of n)r=e.filterFn(r);const i=Ta(o.getRootNode());null===i&&ee("No state tree found on this root for two-way binding.");const a=vt(o);i.createState("writable",e=>{e[Rt](a,()=>{let n=e[t];if(Array.isArray(n))if(s)-1===n.indexOf(r)&&(e[t]=n.concat(r));else{const o=n.indexOf(r);-1!==o&&(e[t]=n.toSpliced(o,1))}else e[t]=s?[r]:[]})})},Pn.set(s,r)),e.node.addEventListener(o,r),In.add(s,e),!0}var t,n;return!1}function An(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function Cn(e,t){console.error(`[wcstack/state] ${t} rejected.`,e)}function En(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)An(e)&&Promise.resolve(e).catch(e=>Cn(e,t))}class Mn{_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)try{t.push(n(...e))}catch(e){t.push(void 0),console.error(`[wcstack/state] a subscriber of token "${this.name}" threw; the remaining subscribers still received it.`,e)}return t}}class On extends Mn{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==xt&&xt({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const Tn=new WeakMap;function Rn(e,t){let n=Tn.get(e);void 0===n&&(n=new Map,Tn.set(e,n));let o=n.get(t);return void 0===o&&(o=new On(t,e),n.set(t,o)),o}const jn=new WeakMap;function Ln(e){if(e.propSegments[0]!==x)return!1;const t=e.node,n=Ke(t),o=Ge(t);if(null!==n&&void 0===o?.get(n))return null===o&&ee(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(jn.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||ee('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===Ke(e)?null:Xe(e)}(t);null===r&&ee(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&ee(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${ie(s,r.knownProperties.keys())}`);const a=i.event,l=e.statePathName,c=e.propModifiers,d=e=>{c.includes(p)&&e.preventDefault(),c.includes(g)&&e.stopPropagation();const n=Ta(t.getRootNode());null===n&&ee("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||ee(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${ie(l,n.eventTokenNames)}${ae}`);const o=vt(t);n.createStateAsync("writable",async t=>{En(t[Rt](o,()=>{const s=null!==o?on(o.listIndex,o.pathInfo.wildcardCount):[];return Rn(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,d),jn.set(e,{eventName:a,handler:d}),!0}class Wn extends Mn{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==xt&&xt({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function Dn(e){return e instanceof Wn}const Bn=new Map,zn=Sn();function Fn(e){const t=e.propModifiers.filter(e=>e===p||e===g).sort().join(",");return`${e.statePathName}::${t}`}const qn=(e,t,n)=>o=>{t.includes(p)&&o.preventDefault(),t.includes(g)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Ta(r);null===i&&ee("No state tree found on this root for event handler.");const a=vt(s),l=e.startsWith(W+".");i.createStateAsync("writable",async t=>{const c=t[Rt](a,()=>{let c=null!==a?a.pathInfo.wildcardCount:0;if(null!==a){const e=i.addressHooks;if(e){const t=e.handlerScope;for(let e=0;e<t.length;e++)c=t[e](i,s,r,a,c)}}const d=null!==a?on(a.listIndex,c):[];if(l){const s=t[jt](bn(n,null));return Dn(s)||ee(`Event binding "${e}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...d)}const u=t[e];return"function"!=typeof u&&ee(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});En(c,`"${e}"`)}).catch(t=>Cn(t,`"${e}"`))};function Vn(e){return"event"===e.bindingType&&e.propName.startsWith($)}function Hn(e){if(!Vn(e))return!1;const t=Fn(e);let n=Bn.get(t);void 0===n&&(n=qn(e.statePathName,e.propModifiers,e.statePathInfo),Bn.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),zn.add(t,e),!0}function Kn(e){if(!Vn(e))return!1;const t=Fn(e),n=Bn.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==zn.countOf(t)&&(zn.remove(t,e)&&Bn.delete(t),!0)}const Un=new Map,Gn=Sn();function Jn(e,t){const n=de(e.inFilters);return`${e.statePathName}::${t}::${n}`}function Xn(e){let t="input";for(const n of e.propModifiers)n.startsWith($)&&(t=n.slice(2));return t}function Qn(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(m)){const o=Xn(e),s=Jn(e,o);let r=Un.get(s);return void 0===r&&(t=e.statePathName,n=e.inFilters,r=e=>{const o=e.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("radio"!==o.type)return void console.warn("[@wcstack/state] event.target is not a radio input element.");if(!1===o.checked)return;let s=o.value;for(const e of n)s=e.filterFn(s);const r=Ta(o.getRootNode());null===r&&ee("No state tree found on this root for two-way binding.");const i=vt(o);r.createState("writable",e=>{e[Rt](i,()=>{e[t]=s})})},Un.set(s,r)),e.node.addEventListener(o,r),Gn.add(s,e),!0}var t,n;return!1}const Yn=new Set(["radio","checkbox"]),Zn=new Set(["value","valueAsNumber","valueAsDate"]);function eo(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(Yn.has(e)&&"checked"===t)return!0;if(Zn.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=Ke(n);if(null!==s){const e=Ge(n)?.get(s);void 0===e&&ee(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=Xe(n);if(o?.knownProperties.has(t))return!0}return!1}let to=1,no=1,oo=1;const so=new WeakMap;function ro(e,t,n){let o=so.get(e);void 0===o&&(o=new Map,so.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=to++,o.set(s,r)),r}function io(e,t){return"to-element"===t?2*e:2*e+1}const ao=new Set;function lo(e){return{transactionId:no++,originBindingId:e,visitedEdges:ao,hop:0}}function co(e,t){const n=new Set(e.visitedEdges);return n.add(t),{transactionId:e.transactionId,originBindingId:e.originBindingId,visitedEdges:n,hop:e.hop+1}}let uo=null;function fo(){return uo}function ho(e,t){const n=uo;uo=e;try{return t()}finally{uo=n}}const po=[];let go=!1;const mo=new Map,yo=Sn(),wo=new WeakMap,bo=e=>e.detail,vo=new WeakMap;const $o=new WeakMap;let xo=0;const So=new WeakMap;function Po(e,t,n,o){const s=de(e.inFilters);return`${e.propName}::${e.statePathName}::${t}::${s}::${function(e){if(null===e)return"n";let t=$o.get(e);return void 0===t&&$o.set(e,t=++xo),`g${t}`}(n)}::${o?"o":"s"}`}const Io=(e,t,n,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==s)l=s(i),s!==bo||r||function(e,t,n){const o=e[t];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${t} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,t)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${t}" key while element.${t} is ${typeof o}`),null===s)return;let r=vo.get(e);void 0===r&&(r=new Set,vo.set(e,r)),r.has(t)||(r.add(t),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${e.tagName.toLowerCase()}> "${t}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${t}, or (e) => e.target.${t}) on that wcBindable property.`))}(a,e,l);else{if(!(e in a))return void console.warn(`[@wcstack/state] Property "${e}" does not exist on target element.`);l=a[e]}let c=l;for(const e of n)c=e.filterFn(c);const d=wo.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(o.enablePropagationContext){const n=ro(a,e,t),s=function(e,t){for(let n=po.length-1;n>=0;n--){const o=po[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,e);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:e,statePathName:t,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==xt&&xt({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:io(n,"to-state"),node:a,member:e}));const r=io(n,"to-state"),i=fo();if(null!==i&&i.visitedEdges.has(r))return void(null!==xt&&xt({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=co(i??lo(n),r)}const f=Ta(a.getRootNode());null===f&&ee("No state tree found on this root for two-way binding.");const h=vt(a),p=()=>{r&&(go=!0);try{f.createState("writable",e=>{e[Rt](h,()=>{e[t]=c})})}finally{r&&(go=!1)}};null!==u?ho(u,p):p()};function ko(e){const t=Ke(e.node);if(null!==t){const n=Ge(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&ee(`CustomElementRegistry is unavailable for <${t}>.`))}if(eo(e.node,e.propName)&&-1===e.propModifiers.indexOf(m)){const t=function(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=Ke(e.node);if(null!==n){const o=Ge(e.node)?.get(n);void 0===o&&ee(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Xe(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith($)&&(t=n.slice(2));return t}(e),n=function(e){if(null!==Ke(e.node)){const t=Xe(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??bo}return null}(e),o=function(e){if(null===Ke(e.node))return!1;const t=Xe(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}(e),s=Po(e,t,n,o);So.set(e,{key:s,eventName:t});let r=mo.get(s);void 0===r&&(r=Io(e.propName,e.statePathName,e.inFilters,n,o),mo.set(s,r)),e.node.addEventListener(t,r),yo.add(s,e)}}const No=new WeakSet;function _o(e){No.add(e)}function Ao(e){return!!No.has(e)&&(No.delete(e),!0)}const Co=new WeakMap;function Eo(e,t){const n=Co.get(e);return!(void 0===n||n<t)&&(n===t?Co.delete(e):Co.set(e,n-t),!0)}const Mo=new WeakSet;function Oo(e){Mo.add(e)}function To(e){return!!Mo.has(e)&&(Mo.delete(e),!0)}let Ro=0;function jo(){Ro--}function Lo(){return Ro>0}class Wo{registry;entries=new Map;constructor(e){this.registry=e}wait(e,t,n=()=>{}){const o=e.toLowerCase();let s=this.entries.get(o);void 0===s&&(s={waiters:new Set},this.entries.set(o,s),this.registry.whenDefined(o).then(()=>this.settle(o,null),e=>this.settle(o,e)));const r={active:!0,resolve:t,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(e){return this.entries.get(e.toLowerCase())?.waiters.size??0}settle(e,t){const n=this.entries.get(e);if(void 0===n)return;this.entries.delete(e);const o=Array.from(n.waiters);n.waiters.clear();for(const e of o)e.active&&(e.active=!1,null===t?e.resolve():e.reject(t))}}const Do=new WeakMap;function Bo(e){let t=Do.get(e);return void 0===t&&(t=new Wo(e),Do.set(e,t)),t}const zo=new Set([I,k,N,P]);function Fo(e,t){let n=null;for(const o of e.propModifiers){const e=o.indexOf("=");if(e<0)continue;const s=o.slice(0,e).trim(),r=o.slice(e+1).trim();s!==y&&s!==w&&ee(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&ee(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function qo(e){return e.propModifiers.some(e=>e.includes("="))}const Vo=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Ho=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Ko(e,t){return"state"===e&&"call"===t?Vo:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function Uo(e){if(!o.enableDirectionalInitialSync)return qo(e)&&ee("init=/sync= modifiers require enableDirectionalInitialSync."),Vo;const t=null===(n=Fo(e,y))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:ee(`Invalid init modifier value "${n}".`);var n;const s=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":ee(`Invalid sync modifier value "${e}".`)}(Fo(e,w));if("event"===e.bindingType)return null!==t&&"none"!==t&&ee("Event bindings only allow init=none."),"call"===s?Ho:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(zo.has(e.propSegments[0]))return Ko("state",s);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&ee(`Binding type "${e.bindingType}" does not support init=${t}.`),Ko(t??"state",s);const r=Xe(e.node);if(null===r)return Ko(t??"state",s);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||ee(`Property "${e.propName}" is not declared by wcBindable.`);const l=t??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||ee(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==s||i||ee(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}function Go(e,t){return"auto"!==t?t:function(e){const t=Ta(e.replaceNode.getRootNode());null===t&&ee("No state tree found on this root for binding.");const n=$n(e);let o=!1;return t.createState("readonly",e=>{o=e[Lt](n)}),o}(e)?"state":"element"}let Jo=0,Xo=0;const Qo=["active","disposed","failed"],Yo=new WeakMap,Zo=new WeakMap,es=new WeakMap,ts=new WeakMap,ns=new WeakMap,os=new WeakMap;function ss(e,t){const n=os.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):os.set(e,new Set([n,t]))):os.set(e,t)}function rs(e){return os.has(e)}function is(e,t){const n=os.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function as(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))as(n,t)}function ls(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class cs{root;observer;constructor(e){this.root=e;const t=globalThis.MutationObserver;this.observer="function"==typeof t?new t(e=>this.handleMutations(e)):null,this.observer?.observe(e,{childList:!0,subtree:!0})}handleMutations(e){const t=[],n=[];for(let o=0;o<e.length;o++){const s=e[o],r=s.removedNodes;if(0===r.length||!Eo(s.target,r.length))for(let e=0;e<r.length;e++)t.push(r[e]);const i=s.addedNodes;for(let e=0;e<i.length;e++)n.push(i[e])}const o=[];for(const e of t)Ao(e)||as(e,e=>{is(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)To(e)&&!Lo()||as(e,e=>{is(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&va(o)}}const ds=new WeakMap;function us(e){let t=ds.get(e);return void 0===t&&(t=new cs(e),ds.set(e,t)),t}function fs(e){const t=de(e.inFilters),n=de(e.outFilters);return[e.bindingType,e.propName,e.propModifiers.join(","),e.statePathName,t,n,e.uuid??""].join("\0")}function hs(e,t,n){const o=Ta(ln(e,n));null===o&&ee("No state tree found on this root for binding.");const s=Ut(o,e.statePathInfo);return function(e,t,n){let o=pn.get(e);void 0===o&&(o=new WeakMap,pn.set(e,o));const s=o.get(t);void 0===s?o.set(t,n):s instanceof Set?s.add(n):s!==n&&o.set(t,new Set([s,n])),null!==xt&&xt({type:"state:binding-added",absoluteAddress:Ht(e,t),binding:n})}(s,t,e),s}function ps(e,t){const n=cn(e,t);return fn(n,e),n}function gs(e,t,n,o){null!==t?hn(t,e):function(e,t,n){const o=pn.get(e);if(void 0===o)return;const s=o.get(t);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(t),null!==xt&&xt({type:"state:binding-removed",absoluteAddress:Ht(e,t),binding:n}))}(n,o,e),xn(e),dn(e)}function ms(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class ys{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(e=null){null!==e&&this.observe(e)}initialize(e,t={},n){const o=t.registerAddress??!0,s={registerAddress:o,registerPathInfo:t.registerPathInfo??o,applyOnReconnect:t.applyOnReconnect??!0},r=[];for(const t of e){const e=this.remember(t,s),o=this.rowOf(e),i=null===o?-1:o.bindings.indexOf(e);if(null!==o&&0===o.phases[i]){const t=o;this.observe(e.replaceNode),s.registerAddress&&null===t.addresses[i]&&null===t.patternPathInfos[i]&&(t.registered=!0,this.registerRowSlot(t,i));continue}const a=es.get(e);void 0===a||"disposed"===a.phase||"failed"===a.phase?(this.start(e,s,n),r.push(e)):(this.observe(a.anchor),s.registerAddress&&null===a.address&&null===a.patternListIndex&&(a.options.registerAddress=!0,this.registerAddress(a)),"active"===a.phase&&this.settleInitialRecord(a),this.settleConnectedSnapshot(a))}return r.filter(e=>this.shouldApplyState(e))}activate(e,t){if(ls(t)&&us(t),null===this.rowPlan)for(const n of e){const e=es.get(n);if(void 0!==e&&e.session===this&&"disposed"!==e.phase&&"failed"!==e.phase){null===e.address&&null===e.patternListIndex&&(e.options.registerAddress=!0,this.registerAddress(e,t)),"active"===e.phase&&this.settleInitialRecord(e),this.settleConnectedSnapshot(e);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,t)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,e,t)}shouldApplyState(e){if(!o.enableDirectionalInitialSync)return qo(e)&&Uo(e),!0;const t=this.rowOf(e);if(null!==t){const n=t.bindings.indexOf(e);if(n>=0){if(!t.registered)return!0;if(2===t.phases[n])return!1;const e=t.plan.slots[n];return 1&t.flags[n]?"state"===e.authority||!e.policy.outputOnly:(t.flags[n]|=1,"state"===e.authority)}}const n=es.get(e);return void 0===n||n.session!==this||(!n.options.registerAddress||"waiting-definition"===n.phase||"failed"!==n.phase&&("active"===n.phase&&this.settleInitialRecord(n),n.initialApplyDone?"state"===n.resolvedAuthority||!n.outputOnlyMember&&!n.observationPending:(n.initialApplyDone=!0,"state"===n.resolvedAuthority)))}getRecord(e){const t=this.rowOf(e),n=null===t?-1:t.bindings.indexOf(e);if(null!==t&&n>=0){let o=Zo.get(t);void 0===o&&Zo.set(t,o=[]);return{id:o[n]??(o[n]=++Jo),info:e,generation:t.generation,phase:Qo[t.phases[n]],teardowns:null}}const o=es.get(e);return o?.session===this?o:null}addTeardown(e,t){const n=es.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(ms(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=Ge(e);null===s&&ee(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e),ss(e,this);const r={node:e,active:!0,cancel:null};let i=this.deferredByNode.get(e);void 0===i&&(i=new Set,this.deferredByNode.set(e,i)),i.add(r),this.deferred.add(r);const a=()=>!!r.active&&(r.active=!1,i?.delete(r),this.deferred.delete(r),!0);return r.cancel=Bo(s).wait(t,()=>{if(a())try{Je(s,e),n()}catch(e){o(e)}},e=>{a()&&o(e)}),()=>{a()&&r.cancel?.()}}disposeBinding(e){const t=this.rowOf(e);if(null!==t){const n=t.bindings.indexOf(e);if(n>=0)return void this.disposeRowSlot(t,n)}const n=es.get(e);void 0!==n&&n.session===this&&this.disposeRecord(n)}get isRowSession(){return null!==this.rowPlan}get currentRowPlan(){return this.rowPlan}disposeBindings(e){for(let t=0;t<e.length;t++)this.disposeBinding(e[t]);if(!(this.rows.size>0))for(const e of Array.from(this.deferred))e.active=!1,e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}destroyRow(e){const t=e.length>0?this.rowOf(e[0]):null;null!==t?(this.destroyRowRecord(t),this.rows.delete(t)):this.destroyRecords()}destroyRowRecord(e){for(let t=0;t<e.bindings.length;t++){const n=e.addresses[t];null!==n&&(hn(n,e.bindings[t]),e.addresses[t]=null),e.phases[t]=1}}dispose(){for(const e of Array.from(this.rows))for(let t=0;t<e.bindings.length;t++)this.disposeRowSlot(e,t);for(const e of Array.from(this.records))this.disposeRecord(e);for(const e of Array.from(this.deferred))e.active=!1,e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;if(0===this.records.size)return!0;for(const e of this.records)if(e.pendingDefinitions>0||e.observationPending)return!1;return!0}destroyRecords(){for(const e of this.rows)this.destroyRowRecord(e);this.rows.clear();for(const e of this.records)null!==e.address&&(hn(e.address,e.info),e.address=null),e.phase="disposed",e.teardowns=null;this.records.clear()}forEachActiveBindingNode(e){for(const t of this.rows)for(let n=0;n<t.bindings.length;n++)0===t.phases[n]&&e(t.bindings[n].node);for(const t of this.records)"active"===t.phase&&e(t.info.node)}rebindAddresses(){const e=[];for(const t of this.rows)for(let n=0;n<t.bindings.length;n++){if(0!==t.phases[n])continue;if(null===t.addresses[n]&&null===t.patternPathInfos[n])continue;const o=t.bindings[n];this.unregisterRowSlot(t,n),this.registerRowSlot(t,n),this.shouldApplyState(o)&&e.push(o)}for(const t of this.records){if("active"!==t.phase)continue;const n=t.info;if(null===t.address&&null===t.patternListIndex)continue;const o="for"===n.bindingType?cn(n):null;if(gs(n,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null,this.registerAddress(t),null!==o){const e=cn(n);e!==o&&kt(o)&&It(e,Pt(o)),e!==o&&Tt(o)&&Et(e,Ct(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return ls(t)?t:null}(e);null!==t&&us(t)}handleMutations(e,t,n){for(const n of t)as(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)as(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&va(o)}handleRemovedNode(e){const t=this.knownBindingsByNode.get(e);if(void 0!==t)if(t instanceof Map)for(const e of t.values())this.disposeBinding(e);else this.disposeBinding(t);const n=this.deferredByNode.get(e);if(void 0!==n)for(const e of Array.from(n))e.active=!1,e.cancel?.(),n.delete(e),this.deferred.delete(e)}handleAddedNode(e,t){const n=this.knownBindingsByNode.get(e);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const e of o){const n=es.get(e);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(e);if(void 0!==o)try{this.start(e,o),o.applyOnReconnect&&this.shouldApplyState(e)&&t.push(e)}catch{}}}knownMapFor(e){const t=this.knownBindingsByNode.get(e);if(t instanceof Map)return t;const n=new Map;if(void 0!==t){let e=ns.get(t);void 0===e&&(e=fs(t),ns.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;ss(n,this);const o=this.knownMapFor(n);let s=ns.get(e);void 0===s&&(s=fs(e),ns.set(e,s));const r=o.get(s);if(void 0!==r){const e=this.optionsByBinding.get(r);return void 0!==e&&(e.registerAddress||=t.registerAddress,e.registerPathInfo||=t.registerPathInfo,e.applyOnReconnect||=t.applyOnReconnect),r}return o.set(s,e),this.optionsByBinding.set(e,{...t}),e}initializeRow(e,t){this.rowPlan=e;const n=e.slots,o=t.length,s={id:++Jo,session:this,generation:++Xo,plan:e,bindings:t,registered:!1,phases:new Array(o).fill(0),flags:new Array(o).fill(0),addresses:new Array(o).fill(null),patternPathInfos:new Array(o).fill(null),patternListIndexes:new Array(o).fill(null)};this.rows.add(s);for(let e=0;e<o;e++){const o=t[e],r=o.replaceNode;if(ss(r,this),this.addKnownRowBinding(r,o,e),Yo.set(o,s),n[e].isEvent){let t=!1;try{t=Hn(o)}catch(t){throw s.phases[e]=2,t}t&&(s.flags[e]|=2)}}}activatePlanRows(e,t,n){const o=t.length>0?this.rowOf(t[0]):null;if(null===o||o.bindings!==t){for(const e of t)this.initialize([e],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});return}o.registered=!0;const s=e.slots;let r=!1;for(let e=0;e<t.length;e++)if(0===o.phases[e])null===o.addresses[e]&&null===o.patternPathInfos[e]&&this.registerRowSlot(o,e,n);else{if(r||(o.generation=++Xo,r=!0,this.rows.add(o)),o.phases[e]=0,o.flags[e]=0,s[e].isEvent){let n=!1;try{n=Hn(t[e])}catch(t){throw o.phases[e]=2,this.runRowSlotTeardowns(o,e),t}n&&(o.flags[e]|=2)}this.registerRowSlot(o,e,n)}}rowOf(e){const t=Yo.get(e);return void 0!==t&&t.session===this?t:null}registerRowSlot(e,t,n){if(null!==e.addresses[t]||null!==e.patternPathInfos[t])return;const o=e.bindings[t],s=rn(o);null!==s?(e.patternPathInfos[t]=hs(o,s,n),e.patternListIndexes[t]=s):e.addresses[t]=ps(o,n)}unregisterRowSlot(e,t){const n=e.addresses[t],o=e.patternPathInfos[t];null===n&&null===o||(gs(e.bindings[t],n,o,e.patternListIndexes[t]),e.addresses[t]=null,e.patternPathInfos[t]=null,e.patternListIndexes[t]=null)}disposeRowSlot(e,t){if(1!==e.phases[t]){e.phases[t]=1,this.runRowSlotTeardowns(e,t);for(let t=0;t<e.phases.length;t++)if(0===e.phases[t])return;this.rows.delete(e)}}runRowSlotTeardowns(e,t){try{this.unregisterRowSlot(e,t)}catch{}if(2&e.flags[t]){e.flags[t]&=-3;try{Kn(e.bindings[t])}catch{}}}addKnownRowBinding(e,t,n){const o=this.knownBindingsByNode.get(e);if(void 0===o)return void this.knownBindingsByNode.set(e,t);if(o instanceof Map)return void o.set("@plan:"+n,t);const s=new Map;s.set("@plan:first",o),s.set("@plan:"+n,t),this.knownBindingsByNode.set(e,s)}start(e,t,n){!function(e){const t=e.node,n=e.replaceNode;t!==n&&null!==t.parentNode&&t.parentNode.replaceChild(n,t)}(e);const o=this.optionsByBinding.get(e)??{...t},s={id:++Jo,info:e,generation:++Xo,phase:"discovered",teardowns:null,session:this,anchor:e.replaceNode,options:o,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:null,resolvedAuthority:null,initialSettled:!1,initialApplyDone:!1,outputOnlyMember:!1,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};es.set(e,s),this.records.add(s),void 0===n&&this.observe(s.anchor);try{s.phase="attaching",this.attachListeners(s),s.options.registerAddress&&this.registerAddress(s,n),0===s.pendingDefinitions&&(s.phase="active")}catch(e){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),e}}attachListeners(e){const t=e.info;Hn(t)?e.eventAttached=!0:t.propSegments[0]!==x?(Qn(t)&&ms(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(m)){const t=Xn(e),n=Jn(e,t),o=Un.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Gn.countOf(n)&&(Gn.remove(n,e)&&Un.delete(n),!0))}return!1}(t)),_n(t)&&ms(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(m)){const t=Nn(e),n=kn(e,t),o=Pn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==In.countOf(n)&&(In.remove(n,e)&&Pn.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(o.enableDirectionalInitialSync&&eo(t.node,t.propName)&&-1===t.propModifiers.indexOf(m)){const n=function(e,t,n){let o=wo.get(e);void 0===o&&(o=new Map,wo.set(e,o));let s=o.get(t);return void 0===s&&(s=new Set,o.set(t,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(t),0===o?.size&&wo.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});ms(e,n)}ko(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{Ln(t)&&ms(e,()=>function(e){if(e.propSegments[0]!==x)return!1;const t=jn.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),jn.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=Ke(e.info.node);if(null===n)return void t();const o=Ge(e.info.node);if(null===o&&ee(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void t();e.phase="waiting-definition",e.pendingDefinitions+=1;const s=e.generation,r=Bo(o).wait(n,()=>{if(this.isAlive(e,s))try{Je(o,e.info.node),t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e))}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))});ms(e,r)}settleInitialRecord(e){if(o.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=Uo(e.info),n=Go(e.info,t.authority);if(e.initialPolicy=t,e.resolvedAuthority=n,e.initialSettled=!0,e.outputOnlyMember=t.outputOnly,e.phase="active",!t.observable)return;if("connect"===t.syncOn&&e.info.node instanceof HTMLElement&&!e.info.node.isConnected)return e.observationPending=!0,void Ro++;this.readProducerSnapshot(e,"call"===t.syncOn)}catch(t){throw e.phase="failed",this.runTeardowns(e),this.records.delete(e),t}}}readProducerSnapshot(e,t){if(!this.isAlive(e,e.generation))return;const n=e.info.node,o=e.info.propName;if(!(o in n))return;const s=e.eventSequence,r=n[o];e.observationPending&&(e.observationPending=!1,jo()),t&&e.eventSequence!==s||(e.hasProducerValue=!0,e.producerValue=r,"element"===e.resolvedAuthority&&function(e,t){let n=t;for(const t of e.inFilters)n=t.filterFn(n);const o=Ta(e.node.getRootNode());null===o&&ee("No state tree found on this root for initial binding sync.");const s=vt(e.node);o.createState("writable",t=>{t[Rt](s,()=>{t[e.statePathName]=n})})}(e.info,r))}settleConnectedSnapshot(e){if(o.enableDirectionalInitialSync&&e.observationPending&&e.info.node instanceof HTMLElement&&e.info.node.isConnected)try{this.readProducerSnapshot(e,!1)}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}}registerAddress(e,t){if(null!==e.address||null!==e.patternListIndex)return;const n=e.info,o=rn(n);if(null!==o?(e.patternPathInfo=hs(n,o,t),e.patternListIndex=o):e.address=ps(n,t),!e.options.registerPathInfo)return;const s=Ta(n.replaceNode.getRootNode());null===s&&ee("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(e,t){return e.generation===t&&es.get(e.info)===e&&"disposed"!==e.phase&&"failed"!==e.phase}disposeRecord(e){"disposed"!==e.phase&&(e.phase="disposed",this.runTeardowns(e),this.records.delete(e))}runTeardowns(e){e.observationPending&&(e.observationPending=!1,jo());const t=e.info;if(null!==e.address||null!==e.patternListIndex)try{gs(t,e.address,e.patternPathInfo,e.patternListIndex),e.address=null,e.patternPathInfo=null,e.patternListIndex=null}catch{}if(e.twowayAttached){e.twowayAttached=!1;try{!function(e){const t=So.get(e);if(void 0===t)return;So.delete(e);const n=mo.get(t.key);void 0!==n&&(e.node.removeEventListener(t.eventName,n),yo.remove(t.key,e)&&mo.delete(t.key))}(t)}catch{}}if(null!==e.teardowns){const t=Array.from(e.teardowns).reverse();e.teardowns=null;for(const e of t)try{e()}catch{}}if(e.eventAttached){e.eventAttached=!1;try{Kn(t)}catch{}}}}function ws(e){let t=ts.get(e);return void 0===t&&(t=new ys(e),ts.set(e,t)),t}function bs(e){return es.get(e)?.session??Yo.get(e)?.session??null}let vs=null;function $s(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const xs=Object.freeze([]);const Ss=new WeakMap;const Ps=new WeakMap;function Is(e){return Ps.get(e)??[]}function ks(e,t){Ps.set(e,t)}const Ns=new WeakMap;function _s(e){return Ns.get(e)??[]}function As(e,t){Ns.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 Cs=0;function Es(){return`u${(Cs++).toString(36)}`}let Ms=0,Os=0;const Ts=Symbol("wcs.listIndex.noValue");class Rs{uuid=Es();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;constructor(e,t,n){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=Ts,this._index=t,this._version=Ms,this._chainGeneration=Os}get index(){return this._index}set index(e){this._index=e,this._version=++Ms,this.indexes[this.position]=e}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}get value(){return this._value}set value(e){this._value=e}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=Ms),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===Os||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=Os),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++Ms,Os++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function js(e,t,n=e){return new Rs(e,t,n)}function Ls(e,t){e.reparent(t)}function Ws(e){return e.homeParentListIndex}function Ds(e,t){e.value=t}function Bs(e,t){const n=e.value;return n!==Ts&&n===t.value}const zs=new WeakMap,Fs=new WeakSet;function qs(e){return Fs.has(e)}function Vs(e,t){const n=Ws(e),o=e.parentListIndex;return null===n||n===o||Fs.has(n)?function(e,t,n){return null!==e&&null!==n&&n!==t&&!!Fs.has(e)&&!Fs.has(n)&&n.position===e.position&&Bs(n,e)}(n,o,t)||function(e,t){return e!==t&&null!==e&&null!==t&&e.position===t.position&&Fs.has(e)&&!Fs.has(t)}(o,t)?t:null:n}function Hs(e){const t=zs.get(e);return void 0===t?null:t}function Ks(e,t){const n=zs.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o){const e=Vs(o,t);if(null!==e)for(const t of n)Ls(t,e)}return n}function Us(e,t){null!==t?zs.set(e,t):zs.delete(e)}const Gs=new WeakMap;function Js(e,t){null===t?Gs.delete(e):Gs.set(e,t)}function Xs(e){const t=Gs.get(e);t&&(t.dirty=!0)}const Qs=Symbol.for("wcstack.transition-runner");function Ys(e){const t=globalThis[Qs];return null==t||"wcs-transition-runner"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.run?null:"function"==typeof t.accepts&&t.accepts(e)?t:null}function Zs(e,t,n){const o=Ys(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const er=[],tr=[];function nr(e){tr.includes(e)||tr.push(e)}function or(e,t=0){const n=er.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?er.push(o):er.splice(n,0,o)}function sr(e){queueMicrotask(()=>{throw e})}class rr{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){for(let t=0;t<tr.length;t++)tr[t](e);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:e,context:t}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(e){const t=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(e),t&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){Mt(),queueMicrotask(()=>{const e=this._queueUpdateRecords,t=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],this._applyChange(e,t)})}hasQueuedPath(e,t){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===e&&n.absoluteAddress.absolutePathInfo.pathInfo.path===t)}testApplyChange(e,t){this._applyChange(e.map((e,n)=>({absoluteAddress:e,context:t?.[n]??null})))}_applyChange(e,n=[]){const o=new Map,s=new Set;for(let t=0;t<e.length;t++){const n=e[t],r=o.get(n.absoluteAddress);null!==xt&&null!=r&&null!==n.context&&r.transactionId!==n.context.transactionId&&xt({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:r.transactionId,winnerTransactionId:n.context.transactionId}),o.set(n.absoluteAddress,n.context),s.add(n.absoluteAddress)}for(let e=0;e<n.length;e++){const t=n[e];o.has(t)||o.set(t,null)}const r=[],i=new Map;o.forEach((e,t)=>{if(null!==e&&e.hop>=32)return console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:t.absolutePathInfo.pathInfo.path,transactionId:e.transactionId,hop:e.hop,maxHops:32}),void(null!==xt&&xt({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop}));const n=gn(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(r.push(t),null!==e&&i.set(t,e));else!1!==n.replaceNode.isConnected&&(r.push(n),null!==e&&i.set(n,e))});try{const e=()=>{i.size>0?va(r,i):va(r)};if(t()||0===r.length)e();else{const t=Zs("state",e);void 0!==t&&t.catch(sr)}}finally{Ot(),function(e){for(const t of er.slice())t.listener(e)}(s)}}}const ir=new rr;function ar(){return ir}const lr=new WeakMap,cr=new WeakMap,dr=new WeakMap,ur=new WeakMap;let fr=!1;const hr=new WeakMap;function pr(e){const t=e.absolutePathInfo.stateElement;let n=hr.get(t);void 0===n&&hr.set(t,n=new Set),n.add(e)}function gr(e){const t=hr.get(e);return void 0===t?null:(hr.delete(e),t)}const mr=new WeakMap,yr=new WeakMap,wr=new WeakMap,br=new WeakMap,vr=new WeakMap,$r=[];function xr(e,t){const n=Sr(e);if(n.recorded.has(t))return;n.recorded.add(t);const o=oe(t).cumulativePaths;if(o.length<2)return;let s=vr.get(e);void 0===s&&vr.set(e,s=new Map);for(let e=0;e<o.length-1;e++){let n=s.get(o[e]);void 0===n&&s.set(o[e],n=new Set),n.add(t)}}function Sr(e){let t=lr.get(e);return void 0===t&&lr.set(e,t={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),t}function Pr(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function Ir(e,t,n){const o=e.get(t);o.delete(n),0===o.size&&e.delete(t)}function kr(e,t,n,o){const s=function(e,t){let n=e.byPath.get(t);return void 0===n&&e.byPath.set(t,n=new Map),n}(e,t);let r=cr.get(o);if(void 0===r&&cr.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(Ir(s,e,o),r.set(t,n),Pr(s,n,o)),!1}return r.set(t,n),Pr(s,n,o),!0}function Nr(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):(o.push(n),!1)}function _r(e,t,n,o,s,r){e.lastValue.set(t,n),s&&(null!==o.listIndex&&Nr(dr,o.listIndex,r)&&function(e){for(let t=e.parentListIndex;null!==t;t=t.parentListIndex){let n=wr.get(t);void 0===n&&wr.set(t,n=new Set),n.add(e)}}(o.listIndex),null!==r.levelListIndex&&Nr(ur,r.levelListIndex,r))}function Ar(e,t,n,o,s){fr=!0;const r=Sr(e);xr(e,t);_r(r,t,s,o,kr(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function Cr(e,t){Sr(e).tracked.add(t)}function Er(e,t){return!0===lr.get(e)?.byPath.has(t)||!0===mr.get(e)?.has(t)}function Mr(e,t,n){if("number"!=typeof t)return;const o=e.indexes[t];if(void 0!==o)for(const t of e.getters)n.push(Jt(e.stateElement,bn(t,o)))}function Or(e,t){if(void 0!==e)for(const n of e)t.push(n)}function Tr(e,t,n,o,s){const r=lr.get(e),i=r?.byPath.get(t),a=mr.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return $r;const l=r.lastValue.has(t),c=r.lastValue.get(t);r.lastValue.set(t,s);const d=[],u=!n||!Object.is(o,s),f=l&&(!n||!Object.is(c,o))&&!Object.is(c,s);if(void 0!==i&&(n&&Or(i.get(o),d),f&&Or(i.get(c),d),u&&Or(i.get(s),d)),void 0!==a)for(const e of a)n&&Mr(e,o,d),f&&Mr(e,c,d),u&&Mr(e,s,d);return d}function Rr(e,t){return!0===vr.get(e)?.has(t)}function jr(e,t){let n=e;for(const e of t){if("object"!=typeof n||null===n)return;n=n[e]}return n}function Lr(e,t,n,o,s=!0){const r=oe(t).segments.length,i=[];for(const a of vr.get(e).get(t)){const t=oe(a).segments.slice(r);if(t.includes(c)){Wr(e,a,i);continue}const l=s?jr(n,t):void 0;for(const n of Tr(e,a,s,l,jr(o,t)))i.push(n)}return i}function Wr(e,t,n){const o=lr.get(e).byPath.get(t);if(void 0!==o)for(const e of o.values())Or(e,n);const s=mr.get(e)?.get(t);if(void 0!==s)for(const e of s)for(let t=0;t<e.indexes.length;t++)Mr(e,t,n)}function Dr(e){const t=ur.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function Br(e){const t=dr.get(e);if(void 0!==t){dr.delete(e),function(e){for(let t=e.parentListIndex;null!==t;t=t.parentListIndex){const n=wr.get(t);void 0!==n&&(n.delete(e),0===n.size&&wr.delete(t))}}(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=cr.get(o),r=s.get(n);s.delete(n),Ir(lr.get(t).byPath.get(n),r,o),null!==e.levelListIndex&&Dr(e)}}}function zr(e){const t=br.get(e);if(void 0!==t){br.delete(e);for(const e of t){const t=mr.get(e.stateElement),n=t.get(e.path);n.delete(e),0===n.size&&t.delete(e.path);const o=yr.get(e.indexes);o.splice(o.indexOf(e),1),0===o.length&&yr.delete(e.indexes)}}}function Fr(e){if(!fr)return;Br(e),zr(e);const t=wr.get(e);if(void 0!==t){wr.delete(e);for(const e of t)Br(e),zr(e),wr.delete(e)}}function qr(e,t,n){if(!fr)return;const o=ur.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=lr.get(e),i=o.byPath.get(s);Ir(i,t,r),Pr(i,n,r),cr.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(Xs(r),ar().enqueueAbsoluteAddress(r,null),pr(r))}}const Vr=new WeakMap,Hr=Object.freeze([]),Kr=new Set;function Ur(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:Hr,s=Array.isArray(n)&&n.length>0?n:Hr,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Hr,o=Array.isArray(t)&&t.length>0?t:Hr;let s=Vr.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Ks(o,e)||[],a=i.length>0?Ws(i[0]):e;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:Kr,deleteIndexSet:new Set(i),addIndexSet:Kr};let t=Ks(s,e);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=js(e,n,a);t.push(o)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:Kr,deleteIndexSet:Kr,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 l={oldIndexes:i,newIndexes:i,changeIndexSet:Kr,deleteIndexSet:Kr,addIndexSet:Kr};if(null!==t)return function(e,t){const n=new Set(t),o=new Set(e),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let t=0;t<e.length;t++)a.set(e[t],t);for(let e=0;e<t.length;e++){const n=t[e];r.has(n)||a.get(n)!==e&&s.add(n)}return{oldIndexes:e,newIndexes:t,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,t);t=[];const n=new Map;for(let e=0;e<o.length;e++){const t=o[e];let s=n.get(t);s||(s=[],n.set(t,s)),s.push(e)}const r=new Set,c=new Set;for(let o=0;o<s.length;o++){const l=s[o],d=n.get(l),u=d&&d.length>0?d.shift():void 0;if(void 0===u){const n=js(e,o,a);t.push(n),c.add(n)}else{const e=i[u];u!==o&&r.add(e),t.push(e)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:c}}finally{void 0!==l&&(!function(e,t,n){let o=Vr.get(e);o||(o=new WeakMap,Vr.set(e,o)),o.set(t,n)}(o,s,l),Us(s,l.newIndexes))}}(e,t,n);!function(e,t){for(let n=0;n<e.length;n++){if(e[n].index!==n){const t=e[n].index;e[n].index=n,qr(e[n],t,n)}Ds(e[n],t[n])}}(o.newIndexes,Array.isArray(n)&&n.length>0?n:Hr),function(e){for(const t of e)Fs.add(t)}(o.deleteIndexSet);for(const e of o.deleteIndexSet)Fr(e);return function(e){for(const t of e)Fs.delete(t)}(o.newIndexes),function(e,t){if(!fr||e===t)return;const n=yr.get(e);if(void 0===n)return;yr.delete(e);const o=yr.get(t);yr.set(t,void 0===o?n:o.concat(n));for(const o of n){o.indexes=t;const n=Sr(o.stateElement).lastValue.get(o.path);if("number"!=typeof n)continue;const s=e[n],r=t[n];if(s!==r)for(const e of[s,r])if(void 0!==e&&!qs(e))for(const t of o.getters){const n=Jt(o.stateElement,bn(t,e));Xs(n),ar().enqueueAbsoluteAddress(n,null),pr(n)}}}(o.oldIndexes,o.newIndexes),o}function Gr(e){if(0===e.changeIndexSet.size||e.addIndexSet.size===e.newIndexes.length)return null;const t=new Map;for(let n=0;n<e.oldIndexes.length;n++)t.set(e.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of e.newIndexes){if(e.addIndexSet.has(i))continue;const a=t.get(i);if(void 0===a)return null;a<s&&(r=!1),s=a,n.push(i),o.push(a)}if(r)return null;const i=function(e){const t=e.length,n=[],o=new Array(t).fill(-1);for(let s=0;s<t;s++){const t=e[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;e[n[o]]<t?r=o+1:i=o}r>0&&(o[s]=n[r-1]),n[r]=s}const s=[];let r=n.length>0?n[n.length-1]:-1;for(;r>=0;)s.push(r),r=o[r];return s.reverse(),s}(o),a=new Set;for(const e of i)a.add(n[e]);return a}const Jr=new WeakSet;const Xr=new WeakMap;function Qr(e){return Xr.get(e)??null}function Yr(e,t){Xr.set(e,t)}const Zr=new WeakMap;function ei(e){return Zr.get(e)??[]}function ti(e,t){Zr.set(e,t)}function ni(e,t){const n=ei(e);for(const e of n)$t(e,t)}const oi=new WeakMap;const si=new WeakMap;function ri(e,t){for(let n=0;n<e.length;n++)if(t.has(e[n]))return!0;return!1}function ii(e,t,n,o,s){const r=function(e,t,n){let o=si.get(e);void 0===o&&si.set(e,o=new Map);const s=o.get(n);if(void 0!==s)return s;const r=n+".",i=t.map((t,o)=>{const s=e.slots[o];if(s.isEvent||s.isIndexBinding)return null;const i=t.statePathInfo.path;if(!i.startsWith(r))return null;const a=i.slice(r.length).split("."),l=[];let c=n;for(const e of a){if("*"===e)return null;c+="."+e,l.push(c)}return{tail:a,prefixes:l}});return o.set(n,i),i}(e,t,o.pathInfo.path),i=s.stateElement.getterPaths,a=0!==(s.stateElement.addressHooks?.readMissing.length??0);let l,c=!1;for(let e=0;e<t.length;e++){const d=t[e];if(!n.shouldApplyState(d))continue;const u=r[e];if(null===u||ri(u.prefixes,i)){wa(d,s);continue}if(s.appliedBindingSet.has(d))continue;c||(l=s.state[jt](o),c=!0);const f=u.tail;let h=l,p=!1;for(let e=0;e<f.length;e++){if(null==h){h=void 0;break}if(a&&!(f[e]in Object(h))){p=!0;break}h=h[f[e]]}p?wa(d,s):(s.appliedBindingSet.add(d),ya(d,s,h))}}function ai(e,t,n){ni(e,t);const o=Is(e),s=Qr(e);if(null!==s&&(s.activate(o,n.rootNode),null!==t&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(e){return oi.get(e)??null}(e);if(null!==r)return void ii(r,o,s,t,n)}for(const e of o){if(null===s){fn(cn(e),e)}(null===s||s.shouldApplyState(e))&&wa(e,n)}}function li(e){if(!e.mounted)return;const t=Is(e),n=Qr(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{hn(cn(o),o)}}!function(e){const t=ei(e);for(let e=0;e<t.length;e++)$t(t[e],null)}(e)}function ci(){return Object.freeze(new Set)}const di=new WeakMap,ui=ci();function fi(e,t){const n=di.get(e);n?n.add(t):di.set(e,new Set([t]))}function hi(e){const t=di.get(e);return void 0!==t?t:ui}function pi(e,t){const n=di.get(e);n&&(n.delete(t),0===n.size&&di.delete(e))}const gi=new Set(["if","elseif","else","for"]);class mi{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(e,t=!1){this._content=e,this._ranged=t;const n=[];for(let t=e.firstChild;null!==t;t=t.nextSibling)n.push(t);this._childNodeArray=n,this._firstNode=this._childNodeArray.length>0?this._childNodeArray[0]:null,this._lastNode=this._childNodeArray.length>0?this._childNodeArray[this._childNodeArray.length-1]:null}get firstNode(){return this._firstNode}get lastNode(){return this._lastNode}get mounted(){return this._mounted}appendTo(e){const t=this._childNodeArray;for(let n=0;n<t.length;n++){const o=t[n];Oo(o),e.appendChild(o)}this._mounted=!0}_movableNodes(){if(!this._ranged||!this._mounted)return this._childNodeArray;const e=this._firstNode,t=this._lastNode;if(null===e||null===t||null===e.parentNode)return this._childNodeArray;const n=[];for(let o=e;null!==o;o=o.nextSibling)if(n.push(o),o===t)return n;return this._childNodeArray}mountAfter(e){const t=e.parentNode;if(t){let n=e;for(const e of this._movableNodes()){if(n.nextSibling!==e){Oo(e);const o=t;e.parentNode===t&&"function"==typeof o.moveBefore?o.moveBefore(e,n.nextSibling):t.insertBefore(e,n.nextSibling)}n=e}}this._mounted=!0}tryDestroy(){const e=Qr(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRow(Is(this));const t=this._childNodeArray;for(let e=0;e<t.length;e++){const n=t[e];null!==n.parentNode&&(_o(n),n.parentNode.removeChild(n))}const n=Is(this);for(let e=0;e<n.length;e++){const t=n[e];gi.has(t.bindingType)&&hi(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const e=Qr(this);null!==e&&(e.isRowSession?e.disposeBindings(Is(this)):e.dispose())}this._teardownBindings()}_teardownBindings(){const e=Is(this);for(let t=0;t<e.length;t++){const n=e[t];gi.has(n.bindingType)&&hi(n.node).forEach(e=>{e.unmount()}),xn(n),dn(n)}}unmount(){{const e=Qr(this);null!==e&&(e.isRowSession?e.disposeBindings(Is(this)):e.dispose())}for(const e of this._childNodeArray)null!==e.parentNode&&(_o(e),e.parentNode.removeChild(e));const e=Is(this);for(let t=0;t<e.length;t++){const n=e[t];gi.has(n.bindingType)&&hi(n.node).forEach(e=>{e.unmount()}),xn(n),dn(n)}this._mounted=!1}}function yi(e){let t=e.topLevelStructural;return void 0===t&&(t=e.topLevelStructural=function(e){const t=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.commentElsePrefix}):`);for(let n=e.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&t.test(n.data))return!0;return!1}(e.fragment)),t}function wi(e){const t=document.createDocumentFragment(),n=new mi(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 bi(e,t,n){const o=document.importNode(t.fragment,!0),s=t.nodeInfos,r=new Array(s.length);for(let e=0;e<s.length;e++){const t=st(o,s[e].nodePath);null===t&&ee(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),mt(t),Ve(t),r[e]=t}const i=n.slots,a=new Array(i.length),l=[];for(let e=0;e<i.length;e++){const t=i[e],n=r[t.nodeIndex],o={...t.template,node:n,replaceNode:n};a[e]=o,t.isIndexBinding&&l.push(o)}const c=function(e,t,n){let o=Sa.get(n);void 0!==o&&o.currentRowPlan===e||(o=new ys,Sa.set(n,o));return o.initializeRow(e,t),o}(n,a,e.node),d=new mi(o);return Yr(d,c),ks(d,a),function(e,t){oi.set(e,t)}(d,n),As(d,l),ti(d,r),fi(e.node,d),d}function vi(e){void 0!==e.uuid&&null!==e.uuid||ee("BindingInfo.uuid is null.");const n=za(e.uuid);n||ee(`Fragment with UUID "${e.uuid}" not found.`);const s=!t()&&yi(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(e){const t=o.enableDirectionalInitialSync,n=[],s=e.nodeInfos;for(let t=0;t<s.length;t++){const o=s[t],r=st(e.fragment,o.nodePath);if(null===r)return null;for(const e of o.parseBindTextResults){const o=e.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=e.propSegments[0];if(s===P||s===x)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Ke(r))return null;if("prop"===o&&eo(r,e.propName))return null;const i=it(e);let a;try{a=Uo({...i,node:r,replaceNode:r})}catch{return null}if(a.observable||"auto"===a.authority)return null;n.push({nodeIndex:t,template:i,isEvent:"event"===o,isIndexBinding:e.statePathName in A,policy:a,authority:a.authority})}}return 0===n.length?null:{directional:t,slots:n}}(n)),null!==r)return bi(e,n,r);const i=document.importNode(n.fragment,!0),a=function(e,t){const[n,o]=function(e,t){const n=[],o=[];for(const s of t){const t=st(e,s.nodePath);if(null===t&&ee(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),ht.has(t))continue;const r=pt(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new ys,r=s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:r,bindingSession:s}}(i,n.nodeInfos);s&&function(e,t){e.appendChild(document.createComment(`wcs-row-end:${t}`))}(i,e.uuid);const l=new mi(i,s);Yr(l,a.bindingSession),ks(l,a.bindingInfos);const c=[];for(const e of a.bindingInfos)e.statePathName in A&&c.push(e);return As(l,c),ti(l,a.nodes),fi(e.node,l),l}const $i=new WeakSet,xi=Symbol.for("wcstack.state.view-transition-naming");function Si(){const e=Ys("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function Pi(e,t,n){const o=function(e){const t=e.firstNode;if(null===t)return null;const n=e.lastNode;for(let e=t;null!==e;e=e.nextSibling){if(e.nodeType===Node.ELEMENT_NODE)return e;if(e===n)break}return null}(e);if(null===o||$i.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[xi]??={counter:0,assigned:0,warned:!1}}();r.assigned>=n.limit?r.warned||(r.warned=!0,console.warn(`[@wcstack/state] auto view-transition-name limit (${n.limit}) reached; further elements are left unnamed. Raise naming-limit on <wcs-view-transition>, or switch to naming="manual" and name only what should morph.`)):($i.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${t}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${t}`))}const Ii=new WeakMap,ki=new WeakMap,Ni=new WeakMap,_i=new WeakMap;function Ai(e,t,n){!function(e,t,n){let o=ki.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,ki.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function Ci(e,t){Ii.set(e,t)}function Ei(e){return e.nodeType===Node.ELEMENT_NODE||(e.nodeType===Node.TEXT_NODE?""!==(e.textContent?.trim()??""):e.nodeType===Node.COMMENT_NODE&&e.data.startsWith("@@wcs-"))}function Mi(e,t){if(null===t)return!1;if(e.nextSibling===t)return!0;const n=e.compareDocumentPosition(t);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}function Oi(e,t,n){if(o=t,!Jr.has(o))return null;var o;let s=null;for(let t=0;t<n.newIndexes.length;t++){const o=n.newIndexes[t],r=n.oldIndexes[t],i=n.addIndexSet.has(o)&&n.deleteIndexSet.has(r)?e.get(r):void 0;void 0!==i&&(s??={byAddedIndex:new Map,reused:new Set},s.byAddedIndex.set(o,i),s.reused.add(i))}return s}const Ti=new Set(["if","elseif","else","for"]);function Ri(e,t){for(const n of Is(e))if(t.appliedBindingSet.delete(n),Ti.has(n.bindingType))for(const e of hi(n.node))Ri(e,t)}function ji(e){for(const t of Is(e)){if(!Ti.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of hi(t.node))ji(n),e&&n.mounted&&(li(n),n.unmount(),pi(t.node,n))}}function Li(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function Wi(e,n,s){const r=Boolean(s);let i;const a=hi(e.node);i=0===a.size?vi(e):a.values().next().value;const l=t(),c=e.uuid??"",d=e.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${Li(e)}`),li(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${Li(e)}`),l){const t=document.createComment(`@@wcs-${d}-start:${c}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),i.mountAfter(t);const n=document.createComment(`@@wcs-${d}-end:${c}:${e.statePathName}`),o=i.lastNode??t;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(e.node);ai(i,vt(e.node),n);const t=Si();null!==t&&Pi(i,"branch",t)}}const Di=new WeakMap;function Bi(e){return Di.get(e)??[]}const zi=new Set;function Fi(){zi.clear()}const qi=Symbol.for("wcstack.trustedTypes.policy");function Vi(){const e=globalThis[qi];return null===e||"object"!=typeof e?null:e}let Hi;let Ki=!1;function Ui(e,t){if(Ki)return;if(!function(){if(void 0!==Hi)return Hi;if(!("trustedTypes"in globalThis))return Hi=!1,Hi;try{document.createElement("div").innerHTML="<i></i>",Hi=!1}catch{Hi=!0}return Hi}())return;Ki=!0;const n="function"==typeof Vi()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/state deliberately does not pass state values through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/state] Writing to "${t}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${n}\nInstall a sanitizing policy before the first binding is applied:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr bind the value as text instead of HTML. See docs/csp.md section 7.`,{element:e,property:t})}const Gi={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 Ji(e,n,s){if(1===e.propSegments.length){const t=e.propSegments[0];"textContent"===t||"innerText"===t?s=null==s?"":String(s):void 0===s&&"innerHTML"===t&&(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 c=i[0],d=r[c];if(d!==s){null!==vs&&null!==d&&"object"==typeof d&&null!==s&&"object"==typeof s&&null!==Ke(r)&&vs.rememberOverwrittenObject(r,c,d);const t="innerHTML"===(l=c)||"outerHTML"===l||"srcdoc"===l,i=()=>{let e=!1;try{r[c]=t?function(e){if("string"!=typeof e)return e;const t=Vi(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(s):s,e=!0}catch(e){t&&Ui(r,c),o.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:e})}if(e){const e=function(e,t){const n=Ke(e);if(null===n)return null;const o=Ge(e)?.get(n);if(void 0===o)return null;const s=Xe(e)?.declaredInputs.get(t);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==e)try{!function(e,t,n){if(null==n)return void e.removeAttribute(t);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);e.setAttribute(t,o)}(r,e,s)}catch(t){o.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:s,error:t})}}};if(o.enablePropagationContext&&eo(r,c)){const t=ro(r,c,e.statePathName),o=io(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??fo()??lo(t);if(a.visitedEdges.has(o))null!==xt&&xt({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const e=co(a,o);ho(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:oo++,writtenValue:n};po.push({receipt:i,node:e});try{return r()}finally{po.pop()}}(r,c,s,t,e.transactionId,i))}}else i()}if(t()){const e=Gi[c];e?e(r,s):(!function(e,t,n){let o=Di.get(e);o||(o=[],Di.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,c,s),a=r,zi.add(a))}return}var a,l;const c=i[0];let d=r[c];for(let e=1;e<i.length-1;e++){const t=i[e];if(null==d)return;d=d[t]}const u=i[i.length-1],f=d[u];if(f!==s){if(Object.isFrozen(d))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:f,newValue:s}));null!==vs&&2===i.length&&"object"==typeof d&&null!==d&&null!==Ke(r)&&(u in d?vs.rememberOverwrittenValue(r,c,u,d[u]):vs.recordInjectedKey(r,c,u));try{d[u]=s}catch(e){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:f,newValue:s,error:e})}}}const Xi=new WeakSet;function Qi(e,t,n){}function Yi(e,t){let n=e;for(;null!==n&&n!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e;n=Object.getPrototypeOf(n)}}function Zi(e,t,n){const o=function(e){const t=[];let n=e;for(;null!==n&&n!==Object.prototype;){for(const e of Object.getOwnPropertyNames(n))t.push(e);n=Object.getPrototypeOf(n)}return t}(e),s=t.length>0?t+l:"";for(const e of n){if(s.length>0&&!e.startsWith(s))continue;const t=e.slice(s.length);t.length>0&&-1===t.indexOf(l)&&o.push(t)}return o}const ea={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},ta={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function na(e,t,n,o){return`[wcs/index-arity] ${e}("${t}") requires ${"$resolve"===e?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${ae}`}function oa(e,t){return`[wcs/recursion-anchor] "${e}" does not match the declared recursion anchor "${t}". This version supports exactly one anchor per state, and "**" must be followed by a well-formed suffix (no second "**", no empty segment, no bare "*" right after "**").`}function sa(e,t){return`$setAll("${e}") ${t}`}function ra(e,t,n){return`[wcs/wildcard-rank] ${e} needs ${t} enclosing loop level(s) but the current scope provides ${n}. Wrap it in that many "for" templates, or use $resolve(path, indexes) to name the row explicitly.${ae}`}function ia(e,t){const n=$n(t);if(n.pathInfo.path in A){const e=vt(t.node);return null===e&&ee(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&ee("ListIndex not found for loopContext:");const n=A[t];void 0===n&&ee(`Invalid index name: ${t}`);const o=nn(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&ee(ra(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[jt](n)}const aa=new WeakSet;function la(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const ca=Object.freeze({[I]:function(e,t,n){const o=e.node,s=e.propSegments[1];null!=n?("boolean"!=typeof n&&ee(`Invalid value for class application: expected boolean, got ${typeof n}. Write "|truthy" if you mean to coerce.`),o.classList.toggle(s,n)):o.classList.toggle(s,!1)},[k]:function(e,t,n){const o=e.node,s=e.propSegments[1];if(null==n)return void(o.hasAttribute(s)&&o.removeAttribute(s));const r=String(n);o.getAttribute(s)!==r&&o.setAttribute(s,r)},[N]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[P]:function(e,t,n){Dn(n)||ee("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=Ss.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||ee('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=Ke(e);if(null===t)return null;const n=Ge(e)?.get(t);return void 0===n&&ee(`Custom element <${t}> is not defined for command binding.`),Xe(e)}(r);null===a&&ee(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||ee(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${ie(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),Ss.delete(e));const l=new WeakRef(r);let c=null;c=o.subscribe((...t)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void Ss.delete(e);const o=n[i];return"function"!=typeof o&&ee(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),Ss.set(e,{token:o,unsubscribe:c,elementRef:l})}}),da={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!Xi.has(e.replaceNode)){Xi.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=rn(e),i=cn(e),a=Pt(i),l=a.length>0&&!ki.has(e.node)?[]:a,d=Ur(r,l,o);n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]);let u=ki.get(e.node);const f=void 0!==u?Oi(u,l,d):null,h=Array.isArray(l)&&l.length===d.deleteIndexSet.size&&d.deleteIndexSet.size>0;if(h&&null===f&&null!==e.node.parentNode){let t=_i.get(e.node);if(void 0===t){const n=Ii.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(Ei(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(Ei(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n),_i.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){Co.set(e,(Co.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let p=h?1e3-function(e){return Ni.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;if(void 0!==u){const t=u;d.deleteIndexSet.forEach(n=>{const o=t.get(n);void 0!==o&&(null!==f&&f.reused.has(o)?(li(o),ji(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?pi(e.node,o):(li(o),o.unmount(),function(e,t){let n=Ni.get(e.node);void 0===n&&(n=[],Ni.set(e.node,n)),n.length<1e3?n.push(t):pi(e.node,t)}(e,o),p-=1),h||t.delete(n))}),h&&(ki.delete(e.node),u=void 0)}let g=e.node;const m=oe(s.path+"."+c),y=n.stateElement.loopContextStack,w=Gr(d);let b=null;d.newIndexes.length==d.addIndexSet.size&&d.newIndexes.length>0&&g.isConnected&&null===f&&(b=document.createDocumentFragment(),Yt(b,n.rootNode));const v=t(),$=Si(),x=e.uuid??"",S=Ni.get(e.node);for(const t of d.newIndexes){let o;if(d.addIndexSet.has(t)){const r=bn(m,t);if(y.createLoopContext(r,r=>{if(o=f?.byAddedIndex.get(t)??(void 0!==S?S.pop():void 0),void 0===o?o=vi(e):Ri(o,n),null!==b)v&&b.appendChild(document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`)),o.appendTo(b),v&&b.appendChild(document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`));else{if(g.nextSibling!==o.firstNode){if(v){const e=document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`);g.parentNode.insertBefore(e,g.nextSibling),g=e}o.mountAfter(g)}if(v){const e=document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`),n=o.lastNode??g;n.parentNode.insertBefore(e,n.nextSibling)}}ai(o,r,n),null!==$&&Pi(o,"row",$)}),void 0===o&&ee(`Content not found for ListIndex: ${t.index} at path "${s.path}"`),null!==f&&f.reused.has(o)){const e=n.stateElement.addressHooks;if(e){const t=e.rowReused;for(let e=0;e<t.length;e++)t[e](n.stateElement,o)}}}else{if(o=void 0!==u?u.get(t)??null:null,d.changeIndexSet.has(t)){const e=_s(o);for(const t of e)wa(t,n)}null===o&&ee(`Content not found for ListIndex: ${t.index} at path "${s.path}"`);const e=!o.mounted;if(null!==w&&w.has(t)&&Mi(g,o.firstNode)||g.nextSibling===o.firstNode||o.mountAfter(g),e){const e=o,s=bn(m,t);y.createLoopContext(s,t=>{ai(e,t,n)})}}g=o.lastNode||g,void 0===u&&(u=new WeakMap,ki.set(e.node,u)),u.set(t,o)}Ii.set(e.node,g),null!==b&&(e.node.parentNode.insertBefore(b,e.node.nextSibling),Yt(b,null))},if:Wi,else:Wi,elseif:Wi,radio:function(e,t,n){const o=e.node,s=$s(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=$s(o.value,e.inFilters),r=Array.isArray(n)?n:xs;o.checked=r.includes(s)}},ua=new WeakMap,fa=new WeakMap,ha=new WeakMap;function pa(){}function ga(e){const t=vs;if(null!==t){const n=e.replaceNode,o=e.propSegments[0];if(t.isComplete(n,o))return Qi;if(t.isDeclared(n,o))return pa}return Ji}function ma(e,t){ya(e,t,ia(t.state,e))}function ya(e,t,n){const o=$s(n,e.outFilters);if(!0===fa.get(e))return void t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement});let s=ua.get(e);if(void 0===s){if(ua.has(e))return s=ga(e),s===Qi&&ua.set(e,s),void s(e,t,o);if(s=da[e.bindingType],void 0===s){const t=e.propSegments[0];if(s=ca[t],ua.set(e,s),void 0===s){Ke(e.replaceNode)?(s=ga(e),s===Qi&&ua.set(e,s)):(s=Ji,ua.set(e,s))}}if(s===Ji){if("SELECT"===e.node.tagName){const n=e.propSegments[0];if("value"===n||"selectedIndex"===n)return t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement}),void fa.set(e,!0)}}s(e,t,o)}else s(e,t,o)}function wa(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=cn(e);if(t.updatedAbsAddressSetByStateElement.has(t.stateElement)){t.updatedAbsAddressSetByStateElement.get(t.stateElement).add(n)}else t.updatedAbsAddressSetByStateElement.set(t.stateElement,new Set([n]))}const n=bs(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==ha.get(e)){const t=Ke(e.replaceNode);if(t&&void 0===Ge(e.replaceNode)?.get(t))return void function(e,t){if(aa.has(e))return;aa.add(e);const n=()=>{aa.delete(e);const t=bs(e);(null===t||t.shouldApplyState(e))&&va([e])},o=n=>{aa.delete(e),la(t,n)},s=bs(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{aa.delete(e),r()})||(aa.delete(e),r()))}const r=Ge(e.replaceNode);if(null===r)return aa.delete(e),void la(t,new Error("CustomElementRegistry is unavailable."));Bo(r).wait(t,()=>{e.replaceNode.isConnected?n():aa.delete(e)},o)}(e,t);ha.set(e,!0)}if(!0===t.sameRootVerified)return void ma(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Zt(o),null===o&&ee("Root node for fragment not found for binding.")),o!==t.rootNode){const n=Ta(o);null===n&&ee("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:t.appliedBindingSet,newListValueByAbsAddress:t.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:t.updatedAbsAddressSetByStateElement,deferredSelectBindings:t.deferredSelectBindings};ma(e,r)})}else ma(e,t)}function ba(e,t,n,o){if(null!==n&&!0===n.hasErrorCallback){const s={path:e.statePathName,bindingType:e.bindingType,node:e.node},r=o.get(n);void 0===r?o.set(n,[{error:t,info:s}]):r.push({error:t,info:s})}else console.error(`[@wcstack/state] binding "${e.bindingType}: ${e.statePathName}" failed to apply; the rest of this batch continues.`,{node:e.node,error:t});null!==xt&&xt({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function va(e,t,n){let s=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;s<e.length;){let n=e[s];if(!1===n.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),s++;continue}let d=n.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=Zt(d),null===d&&ee("Root node for fragment not found for binding."));const u=Ta(d);null===u&&ee("No state tree found on this root for binding."),u.createState("readonly",o=>{const f={rootNode:d,stateElement:u,state:o,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:t};for(;;){try{wa(n,f)}catch(e){ba(n,e,u,c)}s++;const t=e[s];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;n=t}})}for(const{binding:e,value:n,stateElement:o}of l)try{Ji(e,{propagationContextByBinding:t},n)}catch(t){ba(e,t,o??null,c)}for(const[e,t]of i.entries())It(e,t),Et(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[Bt](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[zt](n,o)}catch(e){console.error(`[@wcstack/state] $errorCallback threw while handling the failure of binding "${o.bindingType}: ${o.path}".`,{error:e,original:n,node:o.node})}})}function $a(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=yt(o);if(0===e.length)return;$t(o.node,t);va(n.initialize(e))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}function xa(e,t,n){const[o,s,r]=gt(e,n),i=ws(e);for(const e of o)$t(e,t);va(i.initialize(s)),$a(r,t,i)}const Sa=new WeakMap;async function Pa(e){const t=e.querySelectorAll(o.tagNames.state),n=[],s=Ge(e);null===s&&ee(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const e of t){if(ct(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function Ia(e){if(e===document)await Pa(document),Y(document),il(document,document),xa(document.body,null);else{const t=e;t.host.hasAttribute(o.bindAttributeName)&&await qe(t.host),await Pa(t),Y(t),il(t,t),xa(t,null)}}const ka={watch:"temporal",scan:"temporal",streams:"temporal",scopes:"scopes",dcc:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function Na(e,t){return`[wcs/feature-not-installed] ${t} needs the "${e}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${ka[e]??e}" before the state is defined.`}let _a=null;function Aa(e){return null===_a&&ee(Na("ssr",e)),_a}const Ca=new WeakMap,Ea=new WeakMap,Ma=new Set,Oa=[];function Ta(e){return Ca.get(e)??null}function Ra(e){return Ea.get(e)??Promise.resolve()}const ja=new WeakSet;function La(e){ja.add(e)}function Wa(e,n){const s=Ca.get(e);if(null===n){if(void 0===s)return;Ca.delete(e),Ma.delete(s),null!==xt&&xt({type:"state:element-unregistered",rootNode:e,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;if(void 0===s){const o=!t()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===e.constructor.name||"Document"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{if(o){await Aa('the "enable-ssr" attribute').hydrate(e)||await Ia(e)}else await Ia(e);La(e),fl(),t()}catch(e){n(e)}})});Ea.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await Ia(e),La(e),fl(),t()}catch(e){n(e)}})});Ea.set(e,t)}}void 0!==s&&ee('A state tree is already registered on this root — one <wcs-state> per root in v2. This second element stays unregistered: it keeps the state it loaded and its declarations stay live, but nothing binds to it and disconnecting it runs no cleanup — remove it. Mount additional states onto the tree instead: <wcs-state mount="...">.'),Ca.set(e,n),Ma.add(n);for(let t=0;t<Oa.length;t++)Oa[t](e,n);null!==xt&&xt({type:"state:element-registered",rootNode:e,element:n}),o.debug&&console.debug("State element registered",n)}}const Da=new Map;function Ba(e,t,n){if(null===n)Da.delete(e);else{Da.set(e,n);const o=Ta(t);null===o&&ee("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const e of n.nodeInfos)for(const t of e.parseBindTextResults)o.setPathInfo(t.statePathName,t.bindingType)}}function za(e){return Da.get(e)||null}function Fa(e){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=Te(t.getAttribute(o.bindAttributeName)||"");if(t.localName===o.tagNames.state){if(t.hasAttribute("mount"))return n.filter(e=>e.propSegments[0]!==S);const e=n.find(e=>e.propSegments[0]===S);if(void 0!==e){const t=`on a volume element — a <${o.tagNames.state}> with a "mount" attribute`;ee(1===e.propSegments.length?`[wcs/mount-path-invalid] "${e.propName}" is the reserved namespace for volume injection, so it cannot be bound as an element property. Write one key at a time ("${S}.<key>: <path>") ${t}.`:`[wcs/mount-path-invalid] "${e.propName}: ${e.statePathName}" is a volume injection declaration, and it can only be written ${t}. Add mount="<path>", or bind an element property instead.`)}}return n}if(e.nodeType===Node.COMMENT_NODE){const t=We(e);null===t&&ee("Comment node binding text not found.");const n=za(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=De(t),s=null):s=t,[{...o,uuid:s}]}return[]}let qa;function Va(){return qa??={filterName:"not",args:[]}}const Ha=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Ka(e,t){const n=t+l+c,o=Ie(e,"|");let s,r;if(-1!==o?(s=e.slice(0,o).trim(),r=e.slice(o)):(s=e.trim(),r=""),"."===s)s=n;else{if(!s.startsWith("."))return e;s=n+l+s.slice(1)}return r.length>0?s+r:s}function Ua(e,t){const n=Ha.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+Ka(s,t)+r}function Ga(e,t){const n=ke(e,";");let o=!1;const s=n.map(e=>{const n=e.trim();if(0===n.length)return e;const s=Ie(n,":");if(-1===s)return e;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=Ka(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function Ja(e,t){return Ga(e,t)}function Xa(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=Ua(n.data,t);continue}const o=e;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const e=Ga(r,t);e!==r&&o.setAttribute(n,e)}}}function Qa(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}const Ya=new WeakMap;function Za(e){return Ya.get(e)??null}function el(e){const t=[],n=ft(e);for(const e of n){const n=Fa(e);let o=e;if(e.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==e.parentNode){const t=document.createTextNode("");Ya.set(t,e.data),e.parentNode.replaceChild(t,e),o=t}t.push({nodePath:Qa(o),parseBindTextResults:n})}return t}function tl(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 nl=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),ol=Va();function sl(e,t){const n=t.outFilters;return{...t,outFilters:[...n,ol],bindingType:e}}function rl(e,t,n,o,s,r=!0){tl(t),"string"==typeof o&&Xa(t,o),il(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:el(t)};return void 0!==s&&function(e,t,n){for(const o of e)for(let e=0;e<o.parseBindTextResults.length;e++){const s=o.parseBindTextResults[e];null==s.uuid&&(o.parseBindTextResults[e]=t(s,n))}}(i.nodeInfos,s,o),i}function il(e,t,n,s){const r=o.commentElsePrefix,i=dt(t),a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode(e){const t=e;if(i.length>0&&-1!==i.indexOf(t))return NodeFilter.FILTER_REJECT;if("template"===t.tagName.toLowerCase()){if((t.getAttribute(o.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let l=null;const c=[],d=[];for(;a.nextNode();){const e=a.currentNode;d.push(e)}for(const t of d){let i=t.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=Ja(i,n));let a=Te(i)[0];const d=nl.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=Es();let p=null;const g="for"===u?a.statePathName:n;if("else"===u){null===l&&ee("'else' binding found without preceding 'if' or 'elseif' binding."),a=sl("else",l.parseBindTextResult),p=rl(e,f,a,g,s,!1),Ba(h,e,p);const n=c.at(-1),o=document.createComment(`@@${d}:${h}`);void 0!==n?(t.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:Qa(o),parseBindTextResults:Fa(o)})):t.replaceWith(o)}else if("elseif"===u){null===l&&ee("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=rl(e,f,a,g,s),Ba(h,e,p);const n=document.createComment(`@@${d}:${h}`),o=Es(),i={fragment:document.createDocumentFragment(),parseBindTextResult:sl("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Qa(n),parseBindTextResults:Fa(n)}),Ba(o,e,i);const u=c.at(-1);c.push(i);const m=document.createComment(`@@${r}:${o}`);void 0!==u?(t.remove(),u.fragment.appendChild(m),u.nodeInfos.push({nodePath:Qa(m),parseBindTextResults:Fa(m)})):t.replaceWith(m)}else{p=rl(e,f,a,g,s),Ba(h,e,p);const n=document.createComment(`@@${d}:${h}`);t.replaceWith(n)}"if"===u?(c.length=0,l=p):"elseif"===u?l=p:"else"===u&&(l=null,c.length=0)}}const al=()=>`[${o.bindAttributeName}]`;function ll(e){if(rs(e))return!0;if(!cl(e))return!1;if(e.hasAttribute(o.bindAttributeName))return!1;const t=e.querySelector(al());return null!==t&&rs(t)}function cl(e){return 1===e.nodeType}function dl(e){if(ll(e))return;Y(e),il(e.getRootNode(),e);const t=e.hasAttribute(o.bindAttributeName),n=e.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);xa(t&&s?n:e,null)}const ul=[];function fl(){const e=ul.splice(0,ul.length);for(const t of e)dl(t);a()}const hl={protocol:"wcs-binder",version:1,bind:function(e){var t;cl(e)&&!ll(e)&&(t=e.getRootNode(),ja.has(t)?dl(e):ul.push(e))}};const pl="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let gl=0;async function ml(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++gl}\n`;let s=!1;const r=e=>{e.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{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}`)}}catch(e){throw new Error(function(e,t,n){const o=t?.message??String(t);return n?`The inline <script> of state "${e}" was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL, so script-src must allow blob:. Prefer moving the state into an external file and loading it with src="./state.js", which requires no extra CSP directive. See ${pl}`:`Failed to evaluate the inline <script> of state "${e}": ${o}. If this page sets a Content-Security-Policy, see ${pl}`}(t,e,s),{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function yl(e){try{const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}catch(e){ee(`Failed to load script file: ${e}`)}}class wl{_loopContextStack=Array(u).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&ee("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=u&&ee("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&&ee("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&&ee("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else n.listIndex.length!==n.pathInfo.wildcardCount&&ee(`Cannot push loop context when there is no active loop context: the list index chain (length ${n.listIndex.length}) does not cover the wildcard path (wildcard count ${n.pathInfo.wildcardCount}).`);let s;this._loopContextStack[this._length]=n,this._length++;try{s=t(n)}finally{s instanceof Promise?s.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return s}}const bl={$updatedCallback:M,$streams:z},vl=new WeakSet;function $l(e,t){let n=e;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,t);)n=Object.getPrototypeOf(n);return n}function xl(e){if((null===e||"object"!=typeof e&&"function"!=typeof e)&&ee(`The state must be an object, got ${null===e?"null":typeof e}. Check the source of the state element (json / src / the inline <script>).`),!vl.has(e)){for(const t of Object.keys(bl)){if(!(t in e))continue;const n=bl[t];n in e&&ee(`[wcs/declaration-alias] The state declares both "${t}" and "${n}". "${t}" is the old name of "${n}" (it works through 3.x) — keep "${n}".${ae}`),Object.isExtensible(e)||ee(`[wcs/declaration-alias] The state is not extensible, so the old name "${t}" cannot be rewritten to "${n}". Declare "${n}" directly (the old name works through 3.x only on an extensible state).${ae}`);const o=$l(e,t),s=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,n,{...s,configurable:!0}),o===e&&delete e[t]}vl.add(e)}}const Sl=new WeakMap;function Pl(e,t){let n=Sl.get(e);void 0===n&&(n=new Map,Sl.set(e,n));let o=n.get(t);return void 0===o&&(o=new Wn(t,e),n.set(t,o)),o}const Il=new WeakMap;function kl(e){const t=Il.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 Pl(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:Pl(e,n)}},set(){ee("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){ee("$command namespace is read-only; deleting from it is not allowed.")}});return Il.set(e,n),n}const Nl=Symbol("wcs.notHandled"),_l=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],Al=new Map;function Cl(e,t){Al.set(e,t)}const El=new Map;let Ml=[],Ol=[];function Tl(e,t){El.set(e,t),Ml=Array.from(El.values()).sort((e,t)=>e.order-t.order),Ol=Ml.slice().reverse()}function Rl(e){return El.has(e)}function jl(e,t){for(let n=0;n<Ml.length;n++)Ml[n].activate?.(e,t)}function Ll(e){"readonly"===e.mutability&&ee("This state is readonly.")}const Wl=new Map;class Dl{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(e){const t=e.split("."),n=t.slice();let o=0,s=0,r=0,i="none";const a=[];for(let e=0;e<t.length;e++){const i=t[e];if("*"===i)n[e]="*",a.push(null),o++,r++;else{const t=Number(i);Number.isNaN(t)||(n[e]="*",a.push(t),s++,r++)}}const l=oe(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=e,this.segments=t,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function Bl(e){let t;return Wl.get(e)??(Wl.set(e,t=new Dl(e)),t)}function zl(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?null:nn(n.listIndex,o,n.pathInfo.wildcardCount)}function Fl(e,t){if(!e.untracking&&e.addressStackLength>0){const n=e.lastAddressStack,o=n?.pathInfo??null,s=e.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==t.pathInfo.path&&(s.addDynamicDependency(t.pathInfo.path,o.path),t.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const e=tn(t.pathInfo,o);if(e>0){let r=!1;const i=t.listIndex??null,a=n.listIndex??null;for(let n=0;n<e;n++){if((null!==i?nn(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?nn(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}function ql(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function Vl(e,t,n,o,s){const r=e.addressHooks;if(r){const i=r.readMissing;for(let r=0;r<i.length;r++){const a=i[r](e,t,n,o,s);if(a!==Nl)return a}}return Nl}function Hl(e,t,n,o,s){if(t.pathInfo.segments[0]===W)return function(e,t){let n=e;for(let e=1;e<t.length;e++){if(Object(n)!==n)return;n=Reflect.get(n,t[e])}return n}(kl(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){if(null===t.parentAddress){const r=Vl(s,t,null,n,o);if(r!==Nl)return r;ee(function(e,t,n){return`[${ea.binding}] Path "${e}" does not exist on the state tree.${ie(e,Zi(t,"",n))}${ae}`}(t.pathInfo.path,e,s.getterPaths))}const r=Ul(e,t.parentAddress,n,o);if(null==r)return;const i=t.pathInfo.segments[t.pathInfo.segments.length-1],a=s.addressHooks;if(a&&0!==a.readMissing.length&&i!==c&&!(i in Object(r))){const e=Vl(s,t,Object(r),n,o);if(e!==Nl)return e}if(i===c){const e=t.listIndex?.index??ee(ra(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.get(r,e)}return Reflect.get(r,i)}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 Kl(e,t,n,o,s){const r=Jt(s,t),i=function(e){return Gs.get(e)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=Hl(e,t,n,o,s);return Js(r,{value:l,dirty:!1,generation:a}),l}function Ul(e,t,n,o){Fl(o,t),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,t.pathInfo);const s=o.stateElement,r=s.addressHooks;if(r){const e=r.read;for(let r=0;r<e.length;r++){const i=e[r](s,t,n,o);if(i!==Nl)return i}}return ql(s,t)?Kl(e,t,n,o,s):Hl(e,t,n,o,s)}function Gl(e,t,n,o,s,r){const i=new Map,a=(o,s,r,l,c,d,u)=>{const f=o[s]??null;if(null===f)return void u.push(d);const h=bn(f,r),p=Jt(n.stateElement,h),g=Ct(p),m=Ul(e,h,t,n),y=Ur(r,g,m).newIndexes,w=l[c]??null;if(i.set(p,m),null===w)for(let e=0;e<y.length;e++){const t=y[e];a(o,s+1,t,l,c+1,d.concat(t.index),u)}else{const e=y[w]??ee(`ListIndex not found at index ${w} of ${f.path}`);s+1<o.length?a(o,s+1,e,l,c+1,d.concat(e.index),u):u.push(d.concat(e.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[e,t]of i.entries())Et(e,Array.isArray(t)?t:[]);return l}function Jl(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Ks(Ul(e,bn(a,r),t,n),r);null==l&&ee(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??ee(`ListIndex not found at index ${c} of ${a.path}`)}return r}function Xl(e,t,n,o){"object"==typeof e&&null!==e||ee(`${K} list "${t}": ${n} row at index ${o} must be a plain object (got ${null===e?"null":typeof e}).`);const s=Object.getPrototypeOf(e);s!==Object.prototype&&null!==s&&ee(`${K} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function Ql(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&ee(`${K} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function Yl(e,t,n,o){const s=new Array(e.length),r=new Set;for(let i=0;i<e.length;i++){const a=e[i];Xl(a,n,o,i);const l=Ql(a,t,n,o,i);r.has(l)&&ee(`${K} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Zl(e,t){const n=[];for(const o of Object.keys(t))Object.is(e[o],t[o])||n.push({field:o,value:t[o]});for(const o of Object.keys(e))Object.hasOwn(t,o)||null==e[o]||n.push({field:o,value:null});return n}function ec(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=Ul(e,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=t.pathInfo.lastSegment;if(i===c){const e=t.listIndex?.index;return"number"==typeof e&&e in r}return i in r}const tc=new WeakMap;function nc(e,t){null===t?tc.delete(e):tc.set(e,t)}function oc(e,t,n){const s=bn(oe(e.wildcardParentPaths[t]),n),r=Jt(e.stateElement,s),i=Ct(r),a=e.stateProxy[jt](s),l=Ur(s.listIndex,i,a);e.observedListValueByAbsAddress.set(r,Array.isArray(a)?a:[]);const 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}`),[]}}(l,e.searchType);if(t===e.wildcardPaths.length-1)e.targetListIndexes.push(...c);else for(const n of c)oc(e,t+1,n)}const sc=[];function rc(e,t,n,o,s){return"full"===e.listExpansion||e.stateElement.crossRowListPaths?.has(t)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?e.keyedMergePath===t?{fullRows:sc,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:sc,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const ic=[];function ac(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return ic;let s=null;const r=t+l;for(const e of o){if(e!==t&&!e.startsWith(r))continue;const o=oe(e);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??ic}function lc(e,t,n){const o=[],s=e.ranks,r=(e,t)=>{let n=s.get(e.pathInfo.path)??t;n<t&&(n=t),(o[n]??=[]).push(e)};r(t,0);const i=[];for(let t=0;t<o.length;t++){const s=o[t];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!e.visited.has(a)){e.visited.add(a),n(a),i.length=0,cc(e,a,i);for(let e=0;e<i.length;e++)r(i[e],t+1)}}}}function cc(e,t,n){const o=t.pathInfo.path,s=e.staticMap.get(o);if(s)for(const r of s){const s=oe(r);if(e.listPathSet.has(o)&&s.lastSegment===c){const i=e.stateProxy[jt](t),a=Jt(e.stateElement,t),l=Ct(a),c=Ur(t.listIndex,l,i);e.observedListValueByAbsAddress.set(a,Array.isArray(i)?i:[]);const d=rc(e,o,0,0,c);for(const t of d.fullRows){const o=bn(s,t);e.result.add(o),n.push(o)}if(null!==d.movedRows){const t=ac(e,r,s);if(null===t)for(const t of d.movedRows){const o=bn(s,t);e.result.add(o),n.push(o)}else if(t.length>0)for(const o of d.movedRows)for(const s of t){const t=bn(s,o);e.result.add(t),n.push(t)}}}else{const o=bn(s,t.listIndex);e.result.add(o),n.push(o)}}const r=e.dynamicMap.get(o);if(r)for(const o of r){const s=oe(o),r=[];if(s.wildcardCount>0){const n=tn(t.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&ee(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=nn(t.listIndex,n-1,t.pathInfo.wildcardCount)):o=null;const i={stateElement:e.stateElement,observedListValueByAbsAddress:e.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};oc(i,n,o),r.push(...i.targetListIndexes)}else{null===t.listIndex&&ee(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=nn(t.listIndex,n-1,t.pathInfo.wildcardCount);r.push(e)}}else r.push(null);for(const t of r){const o=bn(s,t);e.result.add(o),n.push(o)}}}function dc(e,t,n,o,s,r,i,a,l){const c=t.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(t),[];const d=function(e,t,n,o){const s=new Map,r=new Map,i=[e];for(r.set(e,0);i.length>0;){const e=i.pop();if(s.has(e))continue;const o=t.get(e),a=n.get(e);let l;l=void 0===o?a??[]:void 0===a?o:o.concat(a),s.set(e,l);for(let e=0;e<l.length;e++){const t=l[e];r.set(t,(r.get(t)??0)+1),s.has(t)||i.push(t)}}const a=new Map,l=new Set,c=[];for(const[e,t]of r)0===t&&(a.set(e,0),l.add(e),c.push(e));for(let e=0;e<c.length;e++){const t=c[e],n=a.get(t)+1;n>o&&ee(`Maximum dependency depth of ${o} exceeded. Possible circular dependency detected at path: ${t}`);const i=s.get(t);for(let e=0;e<i.length;e++){const t=i[e];n>(a.get(t)??-1)&&a.set(t,n);const o=r.get(t)-1;r.set(t,o),0===o&&(l.add(t),c.push(t))}}if(l.size!==s.size){let e=-1;for(const t of l){const n=a.get(t);n>e&&(e=n)}const t=e+1;for(const e of s.keys())l.has(e)||a.set(e,t)}return a}(c,n,o,1e3),u={ranks:d,stateElement:e,observedListValueByAbsAddress:new Map,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null};lc(u,t,a),function(e,t){for(let n=0;n<1e3;n++){const n=gr(e.stateElement);if(null===n)return;n.forEach(n=>{lc(e,bn(n.absolutePathInfo.pathInfo,n.listIndex),t)})}}(u,a);for(const[e,t]of u.observedListValueByAbsAddress)Et(e,t);return Array.from(u.result)}function uc(e,t,n,o,s){const r=e.addressHooks;if(r){const i=r.writeObserve;for(let r=0;r<i.length;r++)i[r](e,t,n,o,s)}}function fc(e,t,n){const o=e.addressHooks;if(o){const s=o.written;for(let o=0;o<s.length;o++)s[o](e,t,n)}}function hc(e,t,n){const o=e.addressHooks;if(o){const s=o.swapped;for(let o=0;o<s.length;o++)s[o](e,t,n)}}function pc(e,t,n,o,s,r){const i=Er(e,t),a=Rr(e,t);if(!i&&!a)return null;const l=[],c=mc(l);return i&&Tr(e,t,n,o,s).forEach(c),a&&Lr(e,t,n?o:r(),s).forEach(c),l}function gc(){return o.enablePropagationContext?fo()??null:null}function mc(e){const t=ar(),n=gc();return o=>{Xs(o),t.enqueueAbsoluteAddress(o,n),e.push(o)}}function yc(e,t,n){if(null===e||0===e.length)return;const o=n.stateElement,s=o.staticDependency,r=o.dynamicDependency,i=ar(),a=gc();for(let n=0;n<e.length;n++){const l=e[n].absolutePathInfo,c=l.pathInfo.path;if(!s.has(c)&&!r.has(c))continue;const d=bn(l.pathInfo,e[n].listIndex);dc(o,d,s,r,o.listPaths,t,"new",e=>{if(e===d)return;const t=Jt(o,e);Xs(t),i.enqueueAbsoluteAddress(t,a)},{listExpansion:"diff"})}}function wc(e,t,n,s,r,i,a="diff"){const l=o.enablePropagationContext?fo()??lo(-1):null,c=ar();c.enqueueAbsoluteAddress(t,l),i&&Xs(t),dc(s.stateElement,e,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",t=>{if(t===e)return;const n=Jt(s.stateElement,t);Xs(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function bc(e,t,n,o,s){s&&(e.getterPaths.has(t)?Xs(n):Js(n,{value:o,dirty:!1,generation:e.stateGeneration}))}function vc(e,t,n,o,s,r,i,a){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,o);const i=Ul(e,n,s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===c){const e=t.listIndex?.index??ee(ra(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.set(i,e,o)}return Reflect.set(i,a,o)}if(!r.stateElement.setterPaths.has(t.pathInfo.path))return Reflect.set(e,t.pathInfo.path,o);r.pushAddress(t),r.beginUntrack();try{return Reflect.set(e,t.pathInfo.path,o,s)}finally{r.endUntrack(),r.popAddress()}}finally{wc(t,n,s,r,i,a)}}function $c(e,t,n,o,s,r,i,a){const d=t.parentAddress??ee(`address.parentAddress is undefined path: ${t.pathInfo.path}`),u=Ul(e,d,s,r)??[];let f=(h=u,tc.get(h)??null);var h;if(null===f){const e=Hs(u)??[];f={value:[...u],listIndexes:[...e]},nc(u,f)}try{return vc(e,t,n,o,s,r,i,a)}finally{const n=f.value.indexOf(o),i=Ul(e,d,s,r)??[],a=Array.isArray(i)?Hs(i)??[]:[],h=t.listIndex.index,p=-1!==n?f.listIndexes[n]:js(d.listIndex,-1);a[h]=p;if(new Set(i).size===f.value.length){for(let e=0;e<a.length;e++)a[e].index=e;nc(u,null),function(e,t,n,o,s,r){const i=r.stateElement,a=ar(),d=Jt(i,e);Pt(d)===n&&(Us(t.value,t.listIndexes),It(d,t.value),function(e){Jr.add(e)}(t.value));a.enqueueRenderOnlyAddress(d);const u=new Map;t.listIndexes.forEach((e,t)=>u.set(e,t));const f=oe(e.pathInfo.path+l+c);for(let e=0;e<o.length;e++){const n=o[e],l=u.get(n);if(l===e)continue;const c=bn(f,n),d=Jt(i,c);if(void 0===l){const n=Xt(i,f,t.listIndexes[e]??null);hc(i,d,n),wc(c,d,s,r,null,ql(i,c),"full");continue}dc(i,c,i.staticDependency,i.dynamicDependency,i.listPaths,s,"new",e=>{const t=Jt(i,e);Xs(t),a.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}}(d,f,i,a,s,r)}}}function xc(e,t,n,o,s){const r=s.stateElement.listKeys;if(null!=r&&Array.isArray(n)){const i=r.get(t.pathInfo.path);if(void 0!==i){const r=Ul(e,t,o,s),a=function(e,t,n,o){const s=Yl(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Yl(r,t,e,"current"),a=new Map;for(let e=0;e<r.length;e++)a.set(i[e],r[e]);const l=new Array(o.length),c=[];for(let e=0;e<o.length;e++){const t=o[e],n=a.get(s[e]);void 0!==n&&n!==t?(l[e]=n,c.push({position:e,oldRow:n,newRow:t})):l[e]=t}return c.length>0?{list:l,matched:c}:null}(t.pathInfo.path,i,r,n);if(null!==a)return function(e,t,n,o,s,r){const i=t.pathInfo.path,a=t.listIndex;null===Hs(o)&&Ur(a,null,o);const d=Ur(a,o,n.list),u=Sc(e,t,n.list,s,r,i),f=oe(i+l+c);for(const t of n.matched){const n=Zl(t.oldRow,t.newRow);if(0===n.length)continue;const o=d.newIndexes[t.position];for(const i of n)void 0!==o?xc(e,bn(oe(f.path+l+i.field),o),i.value,s,r):t.oldRow[i.field]=i.value}return u}(e,t,a,r,o,s)}}return Sc(e,t,n,o,s,null)}function Sc(e,t,n,s,r,i){const a=r.stateElement,l=t.pathInfo.path,d=a.addressHooks;if(d){const e=d.write;for(let o=0;o<e.length;o++){const i=e[o](a,t,n,s,r);if(i!==Nl)return i}}const u=!!go&&(go=!1,!0);if(!(l in e)&&null!==t.parentAddress&&!a.elementPaths.has(l)){const f=Ul(e,t.parentAddress,s,r);if("object"==typeof f&&null!==f){const e=t.pathInfo.lastSegment,h=e===c?t.listIndex?.index:e;let p,g=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const e=void 0!==h&&h in f,t=void 0!==h?f[h]:void 0;if(e&&Object.is(t,n))return!0;p=t,g=!0}const m=pc(a,l,g,p,n,()=>f[h]),y=ql(a,t),w=Jt(a,t);null!==xt&&xt({type:"state:write",absoluteAddress:w,value:n,oldValue:p,hasOldValue:g}),uc(a,l,w,p,g);let b=!1;try{if(void 0===h&&ee(ra(`path "${l}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),d&&0!==d.writeMissing.length&&e!==c&&!(h in f)){const e=d.writeMissing;for(let o=0;o<e.length;o++){b=!0;const i=e[o](a,t,f,h,n,s,r);if(i!==Nl)return i;b=!1}}return Reflect.set(f,h,n)}finally{wc(t,w,s,r,i,y),yc(m,s,r),b?Xs(w):bc(a,l,w,n,y),fc(a,t.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=Ul(e,t,s,r);if(ec(e,t,s,r)&&Object.is(o,n))return!0;f=o,h=!0}const p=pc(a,l,h,f,n,()=>Ul(e,t,s,r)),g=a.elementPaths.has(t.pathInfo.path),m=ql(a,t),y=Jt(a,t);null!==xt&&xt({type:"state:write",absoluteAddress:y,value:n,oldValue:f,hasOldValue:h}),uc(a,l,y,f,h);try{return g?$c(e,t,y,n,s,r,i,m):vc(e,t,y,n,s,r,i,m)}finally{yc(p,s,r),g||bc(a,l,y,n,m),fc(a,t.pathInfo,{value:n})}}function Pc(e,t,n,o){return(t,s,...r)=>{Array.isArray(s)||ee(`$resolve("${t}") requires an explicit indexes array (pass [] when the path has no wildcards) — got `+(null===s?"null":typeof s)+"."),r.length>1&&ee(`$resolve("${t}") takes 2 arguments to read and 3 to write (path, indexes, value) — got ${2+r.length}.`);const i=oe(t);if(o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}s.length!==i.wildcardParentPathInfos.length&&ee(na("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=bn(i,Jl(e,n,o,i,s));if(0===r.length)return Ul(e,a,n,o);Ll(o),xc(e,a,r[0],n,o)}}function Ic(e,t,n,o){const s=Pc(e,0,n,o);return(t,r)=>{const i=oe(t);if(void 0===r||Array.isArray(r)||ee(`$getAll("${t}") requires the indexes to be an array when given (omit them for the loop context, or pass [] to expand every level) — got `+(null===r?"null":typeof r)+"."),o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&ee(na("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=zl(o,i.wildcardPaths[e]);if(t){r=on(t,t.length);break}}if(void 0===r){const e=o.addressStackLength>0?o.lastAddressStack:null,n=e?.listIndex??null;i.wildcardCount>0&&null!==e&&null!==n&&n.length>0&&ee(function(e,t){return`$getAll("${e}") was called without indexes inside the loop context of "${t}", but the path shares no wildcard level with that context, so the context indexes ($1..$n) do not apply. Pass indexes explicitly ([] expands every level).`}(t,e.pathInfo.path)),r=[]}}const a=Gl(e,n,o,i,r,{commitDiffBaseline:!0}),l=[];for(let e=0;e<a.length;e++)l.push(s(i.path,a[e]));return l}}function kc(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return zl(o,s.wildcardPaths.at(-1)??ee(`lastWildcardPath is null: ${t.pathInfo.path}`))??ee(`ListIndex not found: ${t.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<t.pathInfo.wildcardCount;r++){const i=t.pathInfo.wildcardParentPathInfos[r]??ee(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=Ks(Ul(e,bn(i,s),n,o),s)??ee(`ListIndex not found: ${i.path}`),l=t.wildcardIndexes[r]??ee(`wildcardIndex is null: ${t.pathInfo.path}`);s=a[l]??ee(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":ee(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function Nc(e,t,n,o){const s=o.stateElement;return t=>{const r=Bl(t),i=kc(e,r,n,o),a=bn(r.pathInfo,i),l=Jt(s,a),c=ar();c.enqueueAbsoluteAddress(l),function(e,t,n,o,s){const r=Er(e,t),i=Rr(e,t);if(!r&&!i)return;const a=n(),l=[],c=mc(l);r&&Tr(e,t,!1,void 0,a).forEach(c),i&&Lr(e,t,void 0,a,!1).forEach(c),yc(l,o,s)}(s,r.pathInfo.path,()=>Ul(e,a,n,o),n,o),dc(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=Jt(s,e);Xs(t),c.enqueueAbsoluteAddress(t)});const d=s.addressHooks;if(d){const e=d.written;for(let t=0;t<e.length;t++)e[t](s,a.pathInfo)}}}function _c(e,t,n,o){return(t,s,r,i)=>{Ll(o);const a=oe(t);Array.isArray(s)||ee(sa(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&ee(na("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&ee(sa(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&ee(sa(t,"requires an array as the value when { spread: true } is set."));const d=Gl(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&ee(function(e,t,n){return`$setAll("${e}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${t}) but got ${n}. Did the list change between $getAll and $setAll?`}(t,d.length,r.length));const u=[];for(let t=0;t<d.length;t++){const s=Jl(e,n,o,a,d[t]);u.push(bn(a,s))}let f=0;for(let t=0;t<u.length;t++){const s=u[t];let i;if(c){i=r(Ul(e,s,n,o),...d[t])}else i=l?r[t]:r;void 0!==i&&(xc(e,s,i,n,o),f++)}return f}}function Ac(e,t){const n=e.getterPaths;if(0===n.size)return!1;for(const e of oe(t).cumulativePaths)if(n.has(e))return!0;return!1}const Cc=/^\$\d+$/,Ec=`${U}${l}`,Mc=`${G}${l}`,Oc=new WeakMap;function Tc(e,t,n,o){const s=A[t];if(void 0===s&&"string"==typeof t&&36===t.charCodeAt(0)&&Cc.test(t)&&ee(`[wcs/index-param-range] "${t}" is not a valid list index parameter: they run from $1 to $128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&ee(`No active state reference to get list index for "${t.toString()}".`);const e=o.lastAddressStack,n=e?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const r=e?.listIndex;null==r&&ee(`ListIndex not found: ${t.toString()}`);let i=s;const a=e.pathInfo,l=o.stateElement?.addressHooks;if(l){const t=l.indexShift;for(let n=0;n<t.length;n++)i+=t[n](o,e)}const c=nn(r,i,a.wildcardCount);return c?.index??ee(`ListIndex not found: ${t.toString()}`)}if("string"==typeof t){const s=o.stateElement?.addressHooks;if(s){const r=s.get;for(let s=0;s<r.length;s++){const i=r[s](o,t,n,e);if(i!==Nl)return i}}if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>Ic(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>_c(e,0,n,o)(t,s,r,i);case"$postUpdate":return t=>Nc(e,0,n,o)(t);case"$resolve":return(t,s,...r)=>Pc(e,0,n,o)(t,s,...r);case"$dependOn":case"$trackDependency":return e=>function(e,t,n,o){return e=>{-1!==e.indexOf(H)&&ee(`[wcs/recursion-unsupported] ${String(t)}("${e}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===o.addressStackLength&&ee(`No active state reference to track dependency for path "${e}".`);const n=o.lastAddressStack?.pathInfo??ee("Internal error: lastAddressStack is null"),s=o.stateElement;o.stateElement.getterPaths.has(n.path)&&n.path!==e&&s.addDynamicDependency(e,n.path)}}(0,t,0,o)(e);case"$eq":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(Ac(o.stateElement,e))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&Cr(o.stateElement,e),Object.is(n[e],t);let r;o.beginUntrack();try{r=n[e]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&Ar(o.stateElement,e,t,Jt(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=Ac(o.stateElement,e);let i,a=r?n[e]:void 0;o.beginUntrack();try{r||(a=n[e]),i=n[t]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&(r?Cr(o.stateElement,e):Ar(o.stateElement,e,i,Jt(o.stateElement,s),a)),Object.is(a,i)};case"$eqIndex":return(e,t=1)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;null!==s&&null!==s.listIndex||ee(`$eqIndex("${e}") needs a list row scope.`);const r=nn(s.listIndex,t-1,s.pathInfo.wildcardCount);if(null===r&&ee(`$eqIndex("${e}", ${t}): no list index at that level.`),Ac(o.stateElement,e))return o.stateElement.getterPaths.has(s.pathInfo.path)&&Cr(o.stateElement,e),Object.is(n[e],r.index);const i=t===s.pathInfo.wildcardCount;let a,l;o.beginUntrack();try{a=n[e],i&&(l=n[s.pathInfo.wildcardParentPaths[t-1]])}finally{o.endUntrack()}if(o.stateElement.getterPaths.has(s.pathInfo.path)){const t=i?Hs(l):null;null!==t?function(e,t,n,o,s){fr=!0,Sr(e).lastValue.set(t,s),xr(e,t);let r=mr.get(e);void 0===r&&mr.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=yr.get(o);if(void 0===l?yr.set(o,l=[]):a=l.find(n=>n.stateElement===e&&n.path===t),void 0===a){a={stateElement:e,path:t,indexes:o,getters:new Set},l.push(a),i.add(a);const n=o[0]?.parentListIndex??null;if(null!==n){let e=br.get(n);void 0===e&&br.set(n,e=new Set),e.add(a)}}a.getters.add(n)}(o.stateElement,e,s.pathInfo,t,a):function(e,t,n,o,s){fr=!0;const r=Sr(e);xr(e,t),_r(r,t,s,o,kr(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,Jt(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untracked":case"$untrackDependency":return e=>function(e,t,n,o){return e=>{o.beginUntrack();try{return e()}finally{o.endUntrack()}}}(0,0,0,o)(e);case W:return kl(o.stateElement)}if(!t.startsWith(Ec)&&!t.startsWith(Mc))return}const r=Bl(t),i=kc(e,r,n,o),a=bn(r.pathInfo,i);return Ul(e,a,n,o)}if("symbol"==typeof t){const s=function(e){let t=Oc.get(e);return void 0===t&&(t=new Map,Oc.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case Rt:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&ee("already in loop context"),e.setLoopContext(t);try{e.pushAddress(t);try{return n()}finally{e.popAddress()}}finally{e.clearLoopContext()}}(o,e,t);break;case jt:i=t=>Ul(e,t,n,o);break;case Lt:i=t=>ec(e,t,n,o);break;case Wt:i=()=>async function(e,t,n){const o=Reflect.get(e,C);"function"==typeof o&&await o.call(n)}(e,0,n);break;case Dt:i=()=>function(e,t,n){const o=Reflect.get(e,E);"function"==typeof o&&o.call(n)}(e,0,n);break;case Bt:i=t=>function(e,t,n,o){const s=Reflect.get(e,M);let r;if("function"==typeof s){const e=new Set,i={};for(const n of t){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const t=n.absolutePathInfo.pathInfo,s=t.path;if(-1===s.indexOf("#")&&(e.add(s),t.wildcardCount>0)){const e=on(n.listIndex,t.wildcardCount),o=i[s];void 0===o?i[s]=[e]:o.push(e)}}r=s.call(n,Array.from(e),i)}const i=o.stateElement?.addressHooks;if(i){const e=i.updated;for(let s=0;s<e.length;s++)e[s](o.stateElement,t,n)}return r}(e,t,n,o);break;case zt:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,O);"function"==typeof s&&s.call(o,t,n)}(e,t,o,n);break;default:return Reflect.get(e,t,n)}return s.set(t,i),i}}class Rc{_stateElement;_addressStack=Array(u).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=Ta(e);null===n&&ee("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=t}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let e;return this._addressStackIndex>=0&&(e=this._addressStack[this._addressStackIndex]),void 0===e&&ee("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex+1>=u&&(this._hasRepeatedAddress()&&ee(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),ee(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of 128 with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=e}_hasRepeatedAddress(){const e=new Set;for(let t=0;t<=this._addressStackIndex;t++){const n=this._addressStack[t];if(n){if(e.has(n))return!0;e.add(n)}}return!1}_tailAddressPaths(){const e=[];for(let t=this._addressStackIndex;t>=0&&e.length<8;t--){const n=this._addressStack[t];n&&e.push(n.pathInfo.path)}return e}_describeAddressCycle(){const e=this._tailAddressPaths();return`${Array.from(new Set(e)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const e=this._addressStack[this._addressStackIndex];return void 0===e&&ee(`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 untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(e,t,n){return Tc(e,t,n,this)}set(e,t,n,o){return Ll(this),function(e,t,n,o,s){if("string"==typeof t){const r=Bl(t),i=kc(e,r,o,s);return xc(e,bn(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)}deleteProperty(e,t){return Ll(this),Reflect.deleteProperty(e,t)}defineProperty(e,t,n){return Ll(this),Reflect.defineProperty(e,t,n)}}const jc=Promise.resolve(),Lc=new Map;let Wc=[];function Dc(e,t){Lc.set(e,t),Wc=Array.from(Lc.values()).sort((e,t)=>e.order-t.order)}function Bc(e,t){return ee(Na(e,t))}const zc="undefined"==typeof HTMLElement?class{}:HTMLElement;function Fc(e){const t=[];let n=e;for(;n&&n!==Object.prototype;)t.push(n),n=Object.getPrototypeOf(n);const o={};for(let e=t.length-1;e>=0;e--)Object.assign(o,Object.getOwnPropertyDescriptors(t[e]));return o}let qc=null;const Vc=new Set(["for","if","elseif","else"]);function Hc(e,n,o){const s=new Map;for(const e of o){const t=oe(e);if(null===t.lastWildcardPath)continue;const n=s.get(t.lastWildcardPath);void 0===n?s.set(t.lastWildcardPath,[t]):n.push(t)}const r=[],i=new Set,a=t=>{const n=Jt(e,t);if(i.has(n))return;i.add(n);const o=gn(n);if(o instanceof Set?r.push(...o):void 0!==o&&r.push(o),null!==t.listIndex){const e=s.get(t.pathInfo.path);if(void 0!==e)for(const n of e)a(bn(n,t.listIndex))}};Mt();try{if(e.createState("readonly",t=>{for(const o of n){const n=bn(oe(o),null);a(n);try{dc(e,n,e.staticDependency,e.dynamicDependency,e.listPaths,t,"new",a)}catch{}}}),0===r.length)return;const o=function(e){const t=[],n=[];for(const o of e)Vc.has(o.bindingType)?t.push(o):n.push(o);return t.sort((e,t)=>0!==(e.replaceNode.compareDocumentPosition(t.replaceNode)&Node.DOCUMENT_POSITION_FOLLOWING)?-1:1),t.concat(n)}(r),s=()=>{va(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=Zs("state",s);void 0!==i&&i.catch(sr)}finally{Ot()}}const Kc=[[F,"watch"],[q,"scan"],[z,"streams"],[V,"recursion"]];class Uc extends zc{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return Ra(e)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializeFailed=!1;_initializationLanded=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_recursionRegistry=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new wl}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_stateGeneration=0;_pathRegistrations=new Map;_pendingReapplyPaths=null;_generatedPaths=new Set;_watchPaths=null;_scanPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_addressHooks=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_treeless=!1;_connectGeneration=0;constructor(){super(),this._initializePromise=new Promise(e=>{this._resolveInitialize=e}),this._connectedCallbackPromise=new Promise((e,t)=>{this._resolveConnectedCallback=e,this._rejectConnectedCallback=t}),this._loadingPromise=new Promise(e=>{this._resolveLoading=e}),this._setStatePromise=new Promise(e=>{this._resolveSetState=e})}get _state(){return void 0===this.__state&&ee(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){xl(e),function(e){for(let t=0;t<Kc.length;t++){const[n,o]=Kc[t];n in e&&!Rl(o)&&ee(Na(o,`"${n}"`))}}(e);const t=this.__state,n=function(){const e=new Map;return{get:t=>e.get(t),set(t,n){e.set(t,n)}}}();n.set("previousState",t),function(e,t,n){for(let o=0;o<Ml.length;o++)Ml[o].validateEarly?.(e,t,n)}(this,e,n);const o=function(e){const t=new Set,n=e[L];if(void 0===n)return t;Array.isArray(n)||ee(`${L} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||ee(`${L} entries must be non-empty strings.`),e===W&&ee(`${L} entry "${e}" conflicts with the reserved namespace name "${W}".`),t.has(e)&&ee(`${L} entry "${e}" is duplicated.`),t.add(e);return t}(e),s=function(e){const t=new Set,n=e[D];if(void 0===n)return t;Array.isArray(n)||ee(`${D} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||ee(`${D} entries must be non-empty strings.`),t.has(e)&&ee(`${D} entry "${e}" is duplicated.`),t.add(e);return t}(e),r=function(e){const t=e[K];if(void 0===t)return null;"object"==typeof t&&null!==t||ee(`${K} must be an object mapping list paths to key specs.`);const n=new Map;for(const[e,o]of Object.entries(t)){0===e.length&&ee(`${K} entry path must be a non-empty string.`);const t=e.split(l);t.some(e=>0===e.length)&&ee(`${K} entry "${e}" must not contain empty path segments.`),t[t.length-1]===c&&ee(`${K} entry "${e}" must be the list path itself, not the element path (drop the trailing "${l}${c}").`),-1!==e.indexOf(H)&&ee(`[wcs/recursion-unsupported] ${K} entry "${e}" uses "${H}", which ${K} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${l}${c}${l}children").`),"function"!=typeof o?("string"!=typeof o&&ee(`${K} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&ee(`${K} entry "${e}" key field name must be a non-empty string.`),(o.includes(l)||o.includes(c))&&ee(`${K} entry "${e}" key field name "${o}" must be a flat property name ("${l}" / "${c}" are not allowed).`),o in Object.prototype&&ee(`${K} entry "${e}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(e,o)):n.set(e,o)}return n.size>0?n:null}(e);var i;n.set("eventTokenNames",s),function(e,t,n){for(let o=0;o<Ml.length;o++)Ml[o].validate?.(e,t,n)}(this,e,n),function(e,t,n){for(let o=0;o<Ml.length;o++)Ml[o].preCommit?.(e,t,n)}(this,e,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=e,void 0!==t&&qc?.reset(this),this._hasUpdatedCallback=M in e,this._hasErrorCallback=O in e,i=this,Tn.delete(i),function(e,t,n){for(let o=0;o<Ml.length;o++)Ml[o].applyEarly?.(e,t,n)}(this,e,n),function(e,t,n){const o=t[B];if(void 0!==o){"object"==typeof o&&null!==o||ee(`${B} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||ee(`${B} entry "${t}" is not declared in $eventTokens.${ie(t,n)}`),"function"!=typeof s&&ee(`${B} entry "${t}" must be a function.`),Rn(e,t).subscribe(s)}}(this,e,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const a=function(e){const t=new Set,n=new Set,o=Fc(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}}(e);for(const e of a.getterPaths)this._getterPaths.add(e);for(const e of a.setterPaths)this._setterPaths.add(e);!function(e,t,n){for(let o=0;o<Ml.length;o++)Ml[o].apply?.(e,t,n)}(this,e,n),this._listKeys=r,this._rebuildPathInfo(),function(e,t,n){for(let o=0;o<Ml.length;o++)Ml[o].register?.(e,t,n)}(this,e,n),jl(this,null),this._resolveLoading?.()}attributeChangedCallback(e,t,n){this._initialized&&t!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===t?"absent":`"${t}"`}, now ${null===n?"absent":`"${n}"`}). Remove this <${o.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?Aa('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){try{if(this.hasAttribute("state")){return function(e){const t=document.getElementById(e);if(t&&"application/json"===t.type)try{return JSON.parse(t.textContent||"{}")}catch(e){ee("Failed to parse JSON from script element:"+e)}return{}}(this.getAttribute("state"))}if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const e=this.getAttribute("json");return JSON.parse(e)}{const e=this.querySelector('script[type="module"]');if(e)return await ml(e,o.tagNames.state);{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element.`)},6e4),t=await this._setStatePromise;return clearTimeout(e),t}}}{const e=this.getAttribute("src");if(e&&e.endsWith(".json"))return await async function(e){try{const t=await fetch(e);return t.ok||ee(`Failed to fetch JSON file: ${t.statusText}`),await t.json()}catch(e){return console.error("Failed to load JSON file:",e),{}}}(e);if(e&&e.endsWith(".js"))return await yl(e);ee(`Unsupported src file type: ${e}`)}}catch(e){ee(`Failed to initialize state: ${e}`)}}async _initialize(){const e=t()?null:this._loadFromSsrElement();if(null!==e&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),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}return await this._loadingPromise,null!==this._rootNode&&(Wa(this._rootNode,this),!0)}_failInitialization(e){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),ee(e)}_failInitializeLoudly(e,t=!0){if(this._initializationLanded)throw e;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${o.tagNames.state}> failed to initialize.`,e),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(e),t&&null!==this._rootNode&&null===Ta(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),Ea.set(e,n)}(this._rootNode,e),function(e,t,n){for(let o=0;o<Wc.length;o++)Wc[o].initializeFailed?.(e,t,n)}(this,this._rootNode,e)),e}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{C in e&&await e[Wt]()})}_callStateDisconnectedCallback(){this.createState("writable",e=>{E in e&&e[Dt]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(e){for(let t=0;t<Wc.length;t++)if(!0===Wc[t].reconnecting?.(e))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||Ta(this._rootNode)===this||Wa(this._rootNode,this)}else{this.hasAttribute("name")&&this._failInitialization(this.hasAttribute("mount")?'"mount" replaces "name" — a volume has no name of its own. Remove the name attribute.':`The "name" attribute was removed in v2 — there is a single state tree per root. Mount this state onto the tree instead: <wcs-state mount="${this.getAttribute("name")}" ...> and read it as "${this.getAttribute("name")}.<path>".`);const e=function(e){for(let t=0;t<Wc.length;t++){const n=Wc[t].connecting?.(e);if(null!=n)return n}return null}(this);if(null!==e)return void await e;if(this.hasAttribute("mount"))try{Bc("scopes",'the "mount" attribute')}catch(e){this._failInitializeLoudly(e,!1)}const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(J))try{Bc("dcc",`a <${o.tagNames.state}> inside a [${J}] host`)}catch(e){this._failInitializeLoudly(e)}let n=!1;try{const e=function(e){for(let t=0;t<Wc.length;t++){const n=Wc[t].preparing?.(e);if(null!=n)return n}return null}(this);null===e&&this.hasAttribute("bind-component")&&Bc("scopes",'the "bind-component" attribute'),n=await(e??!1)}catch(e){this._failInitializeLoudly(e)}if(n)return;let s=!1;try{s=await this._initialize()}catch(e){this._failInitializeLoudly(e)}if(!s)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const e=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(e)}if(this.hasAttribute("enable-ssr")&&!t()||e!==this._connectGeneration||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr")&&!function(){const e=document.documentElement;return!!e&&"orchestrated"===e.getAttribute("data-wcs-server")}())try{await Aa('the "enable-ssr" attribute').emitSnapshot(this)}catch(e){throw this._rejectConnectedCallback?.(e),e}jl(this,e),this._resolveConnectedCallback?.()}disconnectedCallback(){var e;if(!function(e){for(let t=0;t<Wc.length;t++)if(!0===Wc[t].disconnecting?.(e))return!0;return!1}(this)&&null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&function(e,t){for(let n=0;n<Wc.length;n++)Wc[n].initializeFailureCleared?.(e,t)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Wa(this.rootNode,null),e=this,Il.delete(e),function(e){for(let t=0;t<Ol.length;t++)Ol[t].deactivate?.(e)}(this),this._rootNode=null}}}get initialized(){return this._initialized}get connectedRootNode(){return this._rootNode}clearConnectedRootNode(){this._rootNode=null}markInitialized(){this._initialized=!0}settleInitialization(){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}loadStateFromSource(){return this._loadStateFromSource().then(e=>(xl(e),e))}markTreeless(){this._treeless=!0}failInitializeLoudly(e){return this._failInitializeLoudly(e)}get connectGeneration(){return this._connectGeneration}setWatchPaths(e){this._watchPaths=e}setScanPaths(e){this._scanPaths=e}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(e){this._recursionRegistry=e}addGeneratedPath(e){this._generatedPaths.add(e)}setBoundComponent(e,t){this._boundComponent=e,this._boundComponentStateProp=t}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get hasRecursion(){return null!==this._recursionRegistry}get recursionRegistry(){return this._recursionRegistry}get watchPaths(){return this._watchPaths}get scanPaths(){return this._scanPaths}get elementPaths(){return this._elementPaths}addVolumeWatchPaths(e){if(0===e.size)return;const t=new Set(this._watchPaths??[]);for(const n of e)t.add(n);this._watchPaths=t,this.attachAddressHooks("watch",F)}mergeVolumeListKeys(e){if(0===e.size)return;const t=new Map(this._listKeys??[]);for(const[n,o]of e)t.has(n)&&ee(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),t.set(n,o);this._listKeys=t}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(e){this._listPaths.add(e)}findStateDescriptor(e){return Yi(this._state,e)}defineTreeAccessor(e,t){Object.defineProperty(this._state,e,t),"function"==typeof t.get&&this._getterPaths.add(e),"function"==typeof t.set&&this._setterPaths.add(e),this.setPathInfo(e,"prop","internal")}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&ee("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0,this._attachScopeHooks("bind-component")}get hasGraftedVolumes(){return this._hasGraftedVolumes}get addressHooks(){return this._addressHooks}attachAddressHooks(e,t){const n=function(e,t){const n=Al.get(e);return void 0===n&&ee(Na(e,`"${t}"`)),n}(e,t);null===this._addressHooks&&(this._addressHooks={read:[],readMissing:[],write:[],writeMissing:[],writeObserve:[],written:[],swapped:[],get:[],indexShift:[],handlerScope:[],updated:[],suppressPathDiagnostic:[],rowReused:[]}),function(e,t){for(let n=0;n<_l.length;n++){const o=_l[n],s=t[o];if(void 0===s)continue;const r=e[o];r.includes(s)||r.push(s)}}(this._addressHooks,n)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(e){this.attachAddressHooks("scopes",e)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(e){this._bindableEventMap=e,this.attachAddressHooks("dcc",R)}_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,n="binding"){if("internal"!==n){const o=this._pathRegistrations.get(e);void 0===o?this._pathRegistrations.set(e,{bindingType:t,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(e,{bindingType:t,bound:o.bound||"binding"===n})}if("for"===t&&(this._listPaths.add(e),this._elementPaths.add(e+"."+c)),!this._pathSet.has(e)){const t=oe(e);if(this._pathSet.add(e),qc?.check(this,this.__state,e,n),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=oe(e.parentPath)}}}_rebuildPathInfo(){for(const[e,t]of Array.from(this._pathRegistrations))t.bound&&!this._generatedPaths.has(e)&&this.setPathInfo(e,t.bindingType)}_createState(e,t,n){try{const o=function(e,t,n){const o=new Rc(e,n);return new Proxy(t,o)}(e,this._state,t);return n(o)}finally{}}async createStateAsync(e,t){return await this._createState(this.rootNode,e,t)}createState(e,t){this._createState(this.rootNode,e,t)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(e){this._crossRowListPaths.add(e)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(e){this._indexDependentGetterPaths.add(e)}setInitialState(e){if(!this._initialized)return this._initializeFailed&&ee(`<${o.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(e);!function(e){for(let t=0;t<Wc.length;t++)Wc[t].replacingState?.(e)}(this),(this._hasGraftedVolumes||this._hasMounts)&&ee("Cannot replace the whole state of a tree that has grafted volumes or mounted components: re-setting would silently drop grafted data, tree accessors and mount ledgers (D22). Write the changed paths instead.");const t=this.__state;this._state=e;const n=function(e){const t=new Set;for(const n of e)if(void 0!==n)for(const[e,o]of Object.entries(Fc(n)))e.startsWith("$")||e.includes(c)||"function"==typeof o.value||t.add(e);return t}([t,e]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(e){Hc(this,e,this._pathRegistrations.keys())}}const Gc=[],Jc=[];function Xc(){const e=[];let t=0;for(let n=0;n<Jc.length;n++){const o=Jc[n].deref();void 0!==o&&(e.push(o),Jc[t++]=Jc[n])}return Jc.length=t,e}function Qc(e=customElements){Xc().includes(e)||Jc.push(new WeakRef(e));for(let t=0;t<Gc.length;t++)Gc[t](e);e.get(o.tagNames.state)||e.define(o.tagNames.state,Uc)}function Yc(e){const t=function(){const e=document.documentElement?.lang;if(e)try{return Intl.getCanonicalLocales(e),e}catch{return void console.warn(`[@wcstack/state] <html lang="${e}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===t?e:{...e,locale:t}}function Zc(e,t){const o=Yc(e);var r;o&&((r=o).tagNames&&Object.assign(n.tagNames,r.tagNames),"string"==typeof r.bindAttributeName&&(n.bindAttributeName=r.bindAttributeName),"string"==typeof r.commentTextPrefix&&(n.commentTextPrefix=r.commentTextPrefix),"string"==typeof r.commentForPrefix&&(n.commentForPrefix=r.commentForPrefix),"string"==typeof r.commentIfPrefix&&(n.commentIfPrefix=r.commentIfPrefix),"string"==typeof r.commentElseIfPrefix&&(n.commentElseIfPrefix=r.commentElseIfPrefix),"string"==typeof r.commentElsePrefix&&(n.commentElsePrefix=r.commentElsePrefix),"string"==typeof r.locale&&(n.locale=r.locale),"boolean"==typeof r.debug&&(n.debug=r.debug),"boolean"==typeof r.enableMustache&&(n.enableMustache=r.enableMustache),"boolean"==typeof r.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=r.enableDirectionalInitialSync),"boolean"==typeof r.enablePropagationContext&&(n.enablePropagationContext=r.enablePropagationContext),"boolean"==typeof r.enableContractAnalyzer&&(n.enableContractAnalyzer=r.enableContractAnalyzer),"boolean"==typeof r.sameValueGuard&&(n.sameValueGuard=r.sameValueGuard)),Qc(t),function(){const e=globalThis;void 0===e[s]&&(e[s]=hl)}()}let ed=null;function td(e){return ed??ee(Na("watch",`"$watch" in <wcs-state mount="${e}">`))}let nd=null;const od=Object.freeze([]);const sd="3.3.0",rd=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function id(e,t,n,o){return{node:e,propName:t.propName,statePathName:t.statePathName,bindingType:t.bindingType,inFilters:t.inFilters,outFilters:t.outFilters,origin:n,raw:o}}function ad(e){const t=[],n=new Set,s=new Set,r=e=>{const o=function(e){const t=`${de(e.inFilters)}\0${de(e.outFilters)}`;return[e.statePathName,e.propName,e.bindingType,t].join("\0")}(e);n.has(o)||(n.add(o),t.push(e))},i=e=>{if(s.has(e))return;s.add(e);const t=za(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(id(null,t,"fragment","")),null!=t.uuid&&i(t.uuid)},a=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let e=a.nextNode();null!==e;e=a.nextNode()){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=t.getAttribute(o.bindAttributeName);if(null===n||0===n.length)continue;try{const e=ot(t,Te(n));for(const o of e)r(id(t,o,"attribute",n))}catch{}continue}const t=rd.exec(e.data.trim());if(null===t)continue;const n=t[1]||o.commentTextPrefix,s=t[2],a=za(s);if(null===a){if(n===o.commentTextPrefix)try{r(id(e,De(s),"comment",s))}catch{}}else r(id(e,a.parseBindTextResult,"comment",s)),i(s)}return t}function ld(e){const t=function(e){const t=lr.get(e);return void 0===t?null:{byPath:t.byPath,lastValue:t.lastValue,tracked:t.tracked,watchers:mr.get(e)}}(e);if(null===t)return[];const n=new Set([...t.byPath.keys(),...t.tracked]);if(void 0!==t.watchers)for(const e of t.watchers.keys())n.add(e);const o=[];for(const e of[...n].sort()){const n=t.byPath.get(e);let s=0;if(void 0!==n)for(const e of n.values())s+=e.size;o.push({path:e,tracked:t.tracked.has(e),rows:s,keys:n?.size??0,lists:t.watchers?.get(e)?.size??0,lastValue:t.lastValue.get(e)})}return o}const cd="__WCSTACK_DEVTOOLS_HOOK__";function dd(){const e=globalThis,t=e[cd];if(void 0!==t)return 2!==t.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${t.version}, expected 2. Keeping the existing registry (first-wins).`),t;const n=function(){const e=new Map,t=new Set,n=e=>{if(0===t.size)return void e._setSink(null);const n=e.id;e._setSink(e=>{for(const o of t)o.onEvent?.(n,e)})};return{version:2,sources:e,register(o){if(!e.has(o.id)){e.set(o.id,o),n(o);for(const e of t)e.onSourceRegistered?.(o)}},unregister(n){const o=e.get(n);if(void 0!==o){o._setSink(null),e.delete(n);for(const e of t)e.onSourceUnregistered?.(n)}},addListener(o){t.add(o);for(const t of e.values())n(t),o.onSourceRegistered?.(t);return()=>{if(t.delete(o))for(const t of e.values())n(t)}}}}();return e[cd]=n,n}const ud=e=>{null!==xt&&xt({type:"state:update-batch",addresses:e})};function fd(e){const t=null!==xt;!function(e){xt=e}(e);const n=null!==e;n&&!t?or(ud,0):!n&&t&&function(e){const t=er.findIndex(t=>t.listener===e);-1!==t&&er.splice(t,1)}(ud)}function hd(e){return{rootNode:e.rootNode,element:e,paths:{list:e.listPaths,element:e.elementPaths,getter:e.getterPaths,setter:e.setterPaths},commandTokenNames:e.commandTokenNames,eventTokenNames:e.eventTokenNames,staticDependency:e.staticDependency,dynamicDependency:e.dynamicDependency,watchPaths:e.watchPaths??null,keyedListPaths:void 0===e.listKeys||null===e.listKeys?null:new Set(e.listKeys.keys())}}function pd(e){return Ta(e)??ee("devtools: no state tree on this root")}let gd=null;function md(){if(t())return;if(null!==gd)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:sd,getStateElements(){const e=[];for(const t of Ma)e.push(hd(t));return e},overlays(e){return t=pd(e),null===nd?od:nd(t);var t},keyedSubscriptions:e=>ld(pd(e)),keys(e){const t=pd(e),n=[];return t.createState("readonly",e=>{for(const t of Object.keys(e))if(!t.includes("*")&&!t.startsWith("$")){try{if("function"==typeof e[t])continue}catch{}n.push(t)}}),n},read(e,t,n){let o;return pd(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){pd(e).createState("writable",e=>{void 0!==o&&o.length>0?e.$resolve(t,o,n):e[t]=n})},getDeclaredBindings:e=>ad(e),_setSink:fd};gd=e,dd().register(e)}const yd={name:"devtools",install(){md()}},wd=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),bd=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});const vd=new WeakMap;const $d=new WeakMap,xd=new WeakSet,Sd=new WeakMap;function Pd(e,t,n,o){console.warn(`[@wcstack/state] [${ea[n]}] ${ta[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${ie(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${ae}`),null!==xt&&xt({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const Id={check:function(e,t,n,o){if("internal"===o||void 0===t)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const s=e.addressHooks;if(s){const t=s.suppressPathDiagnostic;for(let o=0;o<t.length;o++)if(t[o](e,n))return}const r=oe(n).segments;if("binding"===o&&r.length<2)return;if(function(e,t){let n=vd.get(e);return void 0===n&&(n=new Set,vd.set(e,n)),!!n.has(t)||(n.add(t),!1)}(e,n))return;if(!0===e.hasRecursion&&null!==e.recursionRegistry.recursiveGetterOwning(n))return;const i=function(e,t,n){if(void 0!==Yi(e,t))return bd;const o=oe(t).segments;let s=e,r="";for(let t=0;t<o.length;t++){const i=o[t],a=r;if(r=0===t?i:r+l+i,t>0&&t<o.length-1&&void 0!==Yi(e,r))return wd;if(Object(s)!==s)return wd;if(i===c){if(!Array.isArray(s)||0===s.length)return wd;s=s[0];continue}const d=Yi(s,i);if(void 0===d)return{existence:"missing",missingSegment:i,candidates:Zi(s,a,n)};if("function"==typeof d.get)return t===o.length-1?bd:wd;s=d.value}return bd}(t,n,e.getterPaths);"missing"===i.existence&&(function(e,t){return!0===Sd.get(e)?.has(t)}(e,n)||("binding"!==o?Pd(e,n,o,i):function(e,t,n){let o=$d.get(e);void 0===o&&(o=new Map,$d.set(e,o));if(o.set(t,n),xd.has(e))return;xd.add(e),setTimeout(()=>function(e){xd.delete(e);const t=$d.get(e);if(void 0===t)return;$d.delete(e);for(const[n,o]of t)Pd(e,n,"binding",o)}(e),0)}(e,n,i)))},reset:function(e){vd.delete(e),$d.delete(e)},markExported:function(e,t){let n=Sd.get(e);void 0===n&&(n=new Set,Sd.set(e,n)),n.add(t),$d.get(e)?.delete(t)}};let kd=!1;function Nd(){kd||(kd=!0,function(e){qc=e}(Id))}const _d={name:"diagnostics",install(){Nd()}};function Ad(e){ee(`filter ${e} requires at least one option`)}function Cd(e){ee(`filter ${e} requires a number as option`)}function Ed(e){ee(`filter ${e} requires a number value`)}function Md(e){ee(`filter ${e} requires a date value`)}const Od={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function Td(e){return!(!e||isNaN(Number(e)))}function Rd(e,t){return Td(e)||Cd(t),Number(e)}function jd(e,t,n){return Rd(e?.[t]??Ad(n),n)}const Ld=e=>t=>{const n=e(t);return e=>null==e?e:n(e)},Wd={eq:(e,t)=>{const n=e?.[0]??Ad("eq"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?"string"!=typeof o?e===o:(Td(n)||Cd("eq"),e===Number(n)):"string"==typeof e?e===n:e===o},ne:(e,t)=>{const n=e?.[0]??Ad("ne"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?"string"!=typeof o?e!==o:(Td(n)||Cd("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==o},not:e=>e=>!e,lt:e=>{const t=jd(e,0,"lt");return e=>("number"!=typeof e&&Ed("lt"),e<t)},le:e=>{const t=jd(e,0,"le");return e=>("number"!=typeof e&&Ed("le"),e<=t)},gt:e=>{const t=jd(e,0,"gt");return e=>("number"!=typeof e&&Ed("gt"),e>t)},ge:e=>{const t=jd(e,0,"ge");return e=>("number"!=typeof e&&Ed("ge"),e>=t)},add:e=>{const t=jd(e,0,"add");return e=>("number"!=typeof e&&Ed("add"),e+t)},sub:e=>{const t=jd(e,0,"sub");return e=>("number"!=typeof e&&Ed("sub"),e-t)},mul:e=>{const t=jd(e,0,"mul");return e=>("number"!=typeof e&&Ed("mul"),e*t)},div:e=>{const t=jd(e,0,"div");return e=>("number"!=typeof e&&Ed("div"),e/t)},mod:e=>{const t=jd(e,0,"mod");return e=>("number"!=typeof e&&Ed("mod"),e%t)},abs:e=>e=>("number"!=typeof e&&Ed("abs"),Math.abs(e)),clamp:e=>{const t=jd(e,0,"clamp"),n=jd(e,1,"clamp");return e=>("number"!=typeof e&&Ed("clamp"),Math.min(Math.max(e,t),n))},toFixed:e=>{const t=Rd(e?.[0]??"0","toFixed");return e=>("number"!=typeof e&&Ed("toFixed"),e.toFixed(t))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&Ed("locale"),e.toLocaleString(t??o.locale))},upper:Ld(e=>e=>String(e).toUpperCase()),lower:Ld(e=>e=>String(e).toLowerCase()),capitalize:Ld(e=>e=>{const t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)}),trim:Ld(e=>e=>String(e).trim()),slice:Ld(e=>{const t=[jd(e,0,"slice")],n=e?.[1];return void 0!==n&&t.push(Rd(n,"slice")),e=>String(e).slice(...t)}),substr:Ld(e=>{const t=jd(e,0,"substr"),n=jd(e,1,"substr");return e=>String(e).substr(t,n)}),padStart:Ld(e=>{const t=jd(e,0,"padStart"),n=e?.[1]??"0";return e=>String(e).padStart(t,n)}),padEnd:Ld(e=>{const t=jd(e,0,"padEnd"),n=e?.[1]??" ";return e=>String(e).padEnd(t,n)}),repeat:Ld(e=>{const t=jd(e,0,"repeat");return e=>String(e).repeat(t)}),reverse:Ld(e=>e=>String(e).split("").reverse().join("")),truncate:Ld(e=>{const t=jd(e,0,"truncate"),n=e?.[1]??"…";return e=>{const o=String(e);return o.length<=t?o:o.slice(0,t)+n}}),join:e=>{const t=e?.[0]??", ";return e=>(Array.isArray(e)||ee(`filter ${"join"} requires an array value`),e.join(t))},int:e=>e=>parseInt(String(e),10),float:e=>e=>parseFloat(String(e)),round:e=>{const t=Math.pow(10,Rd(e?.[0]??"0","round"));return e=>("number"!=typeof e&&Ed("round"),Math.round(e*t)/t)},floor:e=>{const t=Math.pow(10,Rd(e?.[0]??"0","floor"));return e=>("number"!=typeof e&&Ed("floor"),Math.floor(e*t)/t)},ceil:e=>{const t=Math.pow(10,Rd(e?.[0]??"0","ceil"));return e=>("number"!=typeof e&&Ed("ceil"),Math.ceil(e*t)/t)},percent:e=>{const t=Rd(e?.[0]??"0","percent");return e=>("number"!=typeof e&&Ed("percent"),`${(100*e).toFixed(t)}%`)},unit:Ld(e=>{const t=e?.[0]??Ad("unit");return e=>String(e)+t}),date:e=>{const t=e?.[0];return e=>(e instanceof Date||Md("date"),e.toLocaleDateString(t??o.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||Md("time"),e.toLocaleTimeString(t??o.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||Md("datetime"),e.toLocaleString(t??o.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||Md("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}`}},hms:e=>{const t=e?.[0]??":";return e=>{e instanceof Date||Md("hms");const n=e.getHours().toString().padStart(2,"0"),o=e.getMinutes().toString().padStart(2,"0"),s=e.getSeconds().toString().padStart(2,"0");return`${n}${t}${o}${t}${s}`}},falsy:e=>e=>!e,truthy:e=>e=>!!e,defaults:(e,t)=>{const n=e?.[0]??Ad("defaults"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e||o},coalesce:(e,t)=>{const n=e?.[0]??Ad("coalesce"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e??o},boolean:e=>e=>Boolean(e),number:e=>e=>Number(e),string:e=>e=>String(e),nullIfEmpty:e=>e=>""===e?null:e},Dd={eq:[1,1],not:[0,0],ne:[1,1],lt:[1,1],le:[1,1],gt:[1,1],ge:[1,1],add:[1,1],sub:[1,1],mul:[1,1],div:[1,1],mod:[1,1],abs:[0,0],clamp:[2,2],toFixed:[0,1],locale:[0,1],upper:[0,0],lower:[0,0],capitalize:[0,0],trim:[0,0],slice:[1,2],substr:[2,2],padStart:[1,2],padEnd:[1,2],repeat:[1,1],reverse:[0,0],truncate:[1,2],join:[0,1],int:[0,0],float:[0,0],round:[0,1],floor:[0,1],ceil:[0,1],percent:[0,1],unit:[1,1],date:[0,1],time:[0,1],datetime:[0,1],ymd:[0,1],hms:[0,1],falsy:[0,0],truthy:[0,0],defaults:[1,1],coalesce:[1,1],boolean:[0,0],number:[0,0],string:[0,0],nullIfEmpty:[0,0]},Bd=Wd,zd=Wd;let Fd=!1;const qd={name:"formats",install(){Fd||(Fd=!0,ye("input",zd,Dd,Od),ye("output",Bd,Dd,Od))}};function Vd(e){return-1!==e.indexOf(H)}function Hd(e,t){if(t===e.recursiveAnchor)return"";const n=e.recursiveAnchor+l;if(!t.startsWith(n))return null;const o=t.slice(e.recursiveAnchor.length);if(Vd(o))return null;const s=o.slice(1).split(l);return s[0]===c||s.some(e=>0===e.length)?null:o}function Kd(e){return 0===e.length?e:l+Jd(e.slice(1))}function Ud(e,t,n){const o=l+e.repeat,s=t.length<=n.length?t:n,r=t.length<=n.length?n:t;if(!r.endsWith(s))return!1;const i=r.slice(0,r.length-s.length);if(0===i.length)return!0;if(i.length%o.length!==0)return!1;for(let e=0;e<i.length;e+=o.length)if(!i.startsWith(o,e))return!1;return!0}function Gd(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(l,o-1))if(Ud(e,t,n.slice(0,o)))return!0;return!1}function Jd(e){const t=e.split(l);for(let e=0;e<t.length;e++)t[e]===c||Number.isNaN(Number(t[e]))||(t[e]=c);return t.join(l)}function Xd(e,t){const n=e.repeat.split(l),o=l+e.repeat;let s=t;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===l+e.repeatList+l+"length")return!0;for(let e=1;e<n.length;e++)if(s===l+n.slice(0,e).join(l))return!0;return!1}function Qd(e,t,n){n<0&&ee(`Recursion depth must not be negative (got ${n}).`);let o=e.anchor;for(let t=0;t<n;t++)o+=l+e.repeat;const s=o+t;let r=0;for(const e of s.split(l))e===c&&r++;return r>d&&ee(`[wcs/recursion-depth-exceeded] Recursion on "${e.anchor}" reached depth ${n} ("${s}"), which needs ${r} wildcard levels — the limit is 128. Either the data nests deeper than the engine can address, or the tree contains a cycle.`),s}function Yd(e,t){return Qd(e,"",t)}function Zd(e,t,n){if(!n.startsWith(e.anchor))return null;if(t.length>0&&!n.endsWith(t))return null;if(n.length<e.anchor.length+t.length)return null;const o=n.slice(e.anchor.length,n.length-t.length);if(0===o.length)return 0;const s=l+e.repeat;let r=0,i=0;for(;i<o.length;){if(!o.startsWith(s,i))return null;i+=s.length,r++}return r}function eu(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const o=t.accessorFor(n.pathInfo.path);return null!==o?o.depth:function(e,t){const n=e.spec;if(!t.startsWith(n.anchor))return null;const o=l+n.repeat;let s=0,r=n.anchor.length;for(;t.startsWith(o,r);)r+=o.length,s++;return r!==t.length&&46!==t.charCodeAt(r)?null:s}(t,n.pathInfo.path)}function tu(e,t,n){const o=e.recursionRegistry,s=Hd(o.spec,n);null===s&&ee(oa(n,o.spec.recursiveAnchor));const r=eu(t,o);return null===r&&ee(`[wcs/recursion-context] "${n}" uses "**", which is bound to the depth of the recursive getter being evaluated, and there is no recursion context here. Read it from inside a recursive getter or a row getter under "${o.spec.anchor}", or name a concrete depth (for example "${o.spec.anchor}${n.slice(o.spec.recursiveAnchor.length)}"). The depth comes from the innermost frame only: a plain getter reached from a recursive getter has no row of its own, so read "**" in the recursive getter and pass the value on.`),o.concretePathAt(s,r)}function nu(e,t,n,o,s){const r=o.spec,i=[],a=new Map,c=[],d=r.repeatList,u=r.anchorList,f=new Set,h=new Set,p=(e,t,n)=>{const o=e.wildcardParentPathInfos;if(t>=o.length)return void i.push(bn(e,n));const s=g(o[t],n,null).rows;for(let n=0;n<s.length;n++)p(e,t+1,s[n])};function g(o,s,i){const l=bn(o,s),c=Jt(n.stateElement,l),u=Ul(e,l,t,n),h=null===i?null:((e,t,n)=>{if(!Array.isArray(t)||0===t.length)return null;const o=t;return f.has(o)&&ee(`[wcs/recursion-cycle] "${e}" is reachable from itself: the recursion on "${r.anchor}" walked into a list that one of its own ancestors already owns. The data contains a cycle, which this version does not support.`),n.has(o)&&ee(`[wcs/recursion-shared-list] "${e}" is the same array instance as a list reached from another node. The recursion on "${r.anchor}" needs a tree: give each node its own "${d}" array.`),o})(o.path,u,i),p=Ur(s,Ct(c),u);return a.set(c,Array.isArray(u)?u:[]),null!==h&&null!==i&&i.add(h),{rows:p.newIndexes,tracked:h}}const m=(e,t,n)=>{const{rows:r,tracked:a}=g(t,n,h);if(0===r.length)return;const u=(e=>{const t=c[e];if(void 0!==t)return t;const n=o.concretePathAt(s,e),r=0===s.length?n:o.concretePathAt("",e),i={nodePath:r,concretePathInfo:oe(n),childListPathInfo:oe(r+l+d)};return c[e]=i,i})(e),y=a;f.add(y);const w=u.concretePathInfo.wildcardCount===e+1;for(let t=0;t<r.length;t++){const n=r[t];w?i.push(bn(u.concretePathInfo,n)):p(u.concretePathInfo,e+1,n),m(e+1,u.childListPathInfo,n)}f.delete(y)};m(0,oe(u),null);for(const[e,t]of a)Et(e,t);return i}function ou(e,t,n,o,s,r,i){Ll(n);const a=n.stateElement.recursionRegistry,l=Hd(a.spec,o);null===l&&ee(oa(o,a.spec.recursiveAnchor));const c=Kd(l);Array.isArray(s)||ee(sa(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&ee(`[wcs/recursion-setall-form] $setAll("${o}", indexes, …) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Pass [] to broadcast to every depth.`),"function"==typeof r&&ee(sa(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&ee(sa(o,'with "**" does not take { spread: true } — handing a flat array to a tree needs the author to know the walk order, which is not a usable contract.')),function(e,t,n){Xd(e,n)&&ee(`[wcs/recursion-structural-write] "${t}" writes the recursion structure itself (a node, its "${e.repeatList}" list or that list's length, or an object on the way to that list). This version broadcasts to leaf properties only — replacing a node would invalidate the child addresses already resolved for this write.`)}(a.spec,o,c);const d=a.conflictingRecursiveGetter(c);null!==d&&ee(`[wcs/recursion-readonly] "${o}" writes into the recursive getter "${d}", which has no setter — the two name the same family of concrete paths (or this path points inside the value that getter derives). Write the values it derives from instead.`);const u=nu(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(xc(e,u[o],r,t,n),f++);return f}const su={write(e,t){if(!0!==e.hasRecursion)return Nl;const n=e.recursionRegistry.recursiveGetterOwningPath(t.pathInfo);return null!==n&&ee(`[wcs/recursion-readonly] "${t.pathInfo.path}" writes into the recursive getter "${n}" (this path is that getter at one depth, or a path inside the value it derives), which has no setter. Write the values it derives from instead.`),Nl},get(e,t,n,o){if(!0!==e.stateElement.hasRecursion)return Nl;if("$getAll"===t)return(t,s)=>{if(Vd(t)){if(void 0!==s)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=Hd(r.spec,o);null===i&&ee(oa(o,r.spec.recursiveAnchor)),Array.isArray(s)||ee(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes either no indexes (to read the depth of the recursive getter being evaluated) or [] (to walk every depth) — got ${null===s?"null":typeof s}.`),s.length>0&&ee(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Omit the indexes to read the depth of the recursive getter being evaluated, or pass [] to walk every depth.`);const a=nu(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(Ul(e,a[o],t,n));return l}(o,n,e,t,s);t=tu(e.stateElement,e,t)}return Ic(o,0,n,e)(t,s)};if("$setAll"===t)return(t,s,r,i)=>Vd(t)?ou(o,n,e,t,s,r,i):_c(o,0,n,e)(t,s,r,i);if(36!==t.charCodeAt(0)&&Vd(t)){const s=Bl(tu(e.stateElement,e,t)),r=kc(o,s,n,e);return Ul(o,bn(s.pathInfo,r),n,e)}return Nl}};let ru=!1;function iu(e,t){"string"==typeof t&&0!==t.length||ee(`[wcs/recursion-declaration-invalid] ${V} ${e} must be a non-empty string.`);const n=t.split(l);n.some(e=>0===e.length)&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must not contain empty path segments.`),n.length<2&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must name a list element: a property path ending with "${l}${c}" (for example "nodes${l}${c}").`),n[n.length-1]!==c&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must end with "${l}${c}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===c&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must have exactly one "${c}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===H&&ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must not contain "${H}" — the declaration is what gives "${H}" its meaning.`),isNaN(Number(n[o]))||ee(`[wcs/recursion-declaration-invalid] ${V} ${e} "${t}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}const au=new WeakSet;function lu(e){return"function"==typeof e.get&&au.has(e.get)}const cu="[wcs/recursion-declaration-invalid]";class du{spec;_definitions=new Map;_accessors=new Map;_ownerByPath=new Map;_ownerByPathInfo=new WeakMap;_accessorByPathInfo=new WeakMap;_concreteBySuffix=new Map;_registeredListPaths=new Set;constructor(e,t){this.spec=e;const n=Fc(t);for(const[t,o]of Object.entries(n)){if(!Vd(t))continue;"function"==typeof o.set&&ee(`${cu} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&ee(`${cu} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Hd(e,t);null===n&&ee(oa(t,e.recursiveAnchor)),0===n.length&&ee(`${cu} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${l}total"), not the node.`),Xd(e,Kd(n))&&ee(`${cu} "${t}" names the recursion structure itself (a node, its "${e.repeatList}" list or that list's length, or an object on the way to that list). A recursive getter would hide the real child list at every depth — "**" names a computed leaf under a node (for example "${e.recursiveAnchor}${l}total").`),this._definitions.set(t,{recursivePath:t,suffix:n,get:o.get})}this._assertNoColliding(),this._assertNoConcreteCollision(n)}_assertNoConcreteCollision(e){for(const[t,n]of Object.entries(e)){if(Vd(t)||lu(n))continue;const e=this._matchExpansion(t);null!==e&&ee(`${cu} "${t}" is already defined on the state, so the recursive getter "${e}" cannot expand to it. Rename one of them.`)}}_assertNoColliding(){const e=Array.from(this._definitions.values());for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++)Ud(this.spec,e[t].suffix,e[n].suffix)&&ee(`${cu} "${e[t].recursivePath}" and "${e[n].recursivePath}" expand to the same concrete path at different depths (they differ by whole repetitions of "${this.spec.repeat}"). Rename one of them.`)}get hasDefinitions(){return this._definitions.size>0}conflictingRecursiveGetter(e){for(const t of this._definitions.values())if(Gd(this.spec,t.suffix,e))return t.recursivePath;return null}recursiveGetterOwningPath(e){const t=this._ownerByPathInfo.get(e);if(void 0!==t)return t;const n=this.recursiveGetterOwning(e.path);return this._ownerByPathInfo.set(e,n),n}recursiveGetterOwning(e){const t=this._accessors.get(e);if(void 0!==t)return t.recursivePath;const n=Jd(e),o=this._ownerByPath.get(n);if(void 0!==o)return o;let s=null;if(n.startsWith(this.spec.anchor)){s=this._matchExpansion(n);for(let e=n.lastIndexOf(l);null===s&&e>this.spec.anchor.length;e=n.lastIndexOf(l,e-1))s=this._matchExpansion(n.slice(0,e))}return this._ownerByPath.set(n,s),s}_matchExpansion(e){for(const t of this._definitions.values())if(null!==Zd(this.spec,t.suffix,e))return t.recursivePath;return null}materializeForPathInfo(e,t){if(0===this._definitions.size)return null;const n=this._accessorByPathInfo.get(t);if(void 0!==n)return n;const o=this.materializeFor(e,t.path);return this._accessorByPathInfo.set(t,o),o}materializeFor(e,t){const n=this._accessors.get(t);if(void 0!==n)return n;if(!t.startsWith(this.spec.anchor))return null;let o=null,s=0;for(const e of this._definitions.values()){const n=Zd(this.spec,e.suffix,t);null!==n&&(null!==o&&ee(`"${t}" matches both "${o.recursivePath}" and "${e.recursivePath}".`),o=e,s=n)}return null===o?null:this._define(e,o,s,t)}_define(e,t,n,o){const s=e.findStateDescriptor(o);void 0===s||lu(s)||ee(`"${o}" is already defined on the state, so the recursive getter "${t.recursivePath}" cannot expand to it. Rename one of them.`);const r=Object.freeze({recursivePath:t.recursivePath,depth:n}),i=t.get,a=function(){return i.call(this)};var l;return l=a,au.add(l),e.defineTreeAccessor(o,{get:a,enumerable:!1,configurable:!0}),this._registerListPaths(e,n),this._accessors.set(o,r),r}_registerListPaths(e,t){for(const n of function(e,t){const n=[];n.push(e.anchorList);for(let o=0;o<t;o++)n.push(Yd(e,o)+l+e.repeatList);return n}(this.spec,t))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),e.addListPath(n))}forgetGenerated(e,t){const n=new Set(this._accessors.keys());return function(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&lu(n)&&delete t[e]}for(const t of[e.staticDependency,e.dynamicDependency]){for(const e of n)t.delete(e);for(const[e,o]of t){let s=null;for(let e=0;e<o.length;e++)n.has(o[e])?s??=o.slice(0,e):s?.push(o[e]);null!==s&&(0===s.length?t.delete(e):t.set(e,s))}}}}(e,t,n),n}concretePathAt(e,t){let n=this._concreteBySuffix.get(e);void 0===n&&(n=[],this._concreteBySuffix.set(e,n));let o=n[t];return void 0===o&&(o=Qd(this.spec,e,t),n[t]=o),o}accessorFor(e){return this._accessors.get(e)??null}get materializedPaths(){return new Set(this._accessors.keys())}}const uu="recursionSpec",fu="recursionRegistry",hu={order:5,validateEarly(e,t,n){const o=function(e){const t=e[V];if(void 0===t)return null;"object"==typeof t&&null!==t||ee(`[wcs/recursion-declaration-invalid] ${V} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(t);0===n.length&&ee(`[wcs/recursion-declaration-invalid] ${V} must declare exactly one anchor; it is empty.`),n.length>1&&ee(`[wcs/recursion-declaration-invalid] ${V} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];iu("anchor",o),"string"!=typeof s&&ee(`[wcs/recursion-declaration-invalid] ${V} entry "${o}" must map to the repeating sub-path as a string (for example "children${l}${c}").`),iu("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(l)),i=s.slice(0,s.lastIndexOf(l)),a=r+l+H;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(t);n.set(uu,o),n.set(fu,null===o?null:new du(o,t))},preCommit(e,t,n){const o=e.recursionRegistry;if(null!==o)for(const t of o.forgetGenerated(e,n.get("previousState")))e.addGeneratedPath?.(t);const s=n.get(fu)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",V)},apply(e,t,n){const o=n.get(uu)??null;null!==o&&e.addListPath(o.anchorList)}};let pu=!1;function gu(){pu||(pu=!0,ru||(ru=!0,Cl("recursion",su)),Tl("recursion",hu))}const mu={name:"recursion",install(){gu()}};const yu={written:function(e,t,n){const o=e.bindableEventMap,s=o[t.path],r="string"==typeof s,i=r?s:t.segments.length>1?o[t.segments[0]]:void 0;if("string"!=typeof i)return;const a=e.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}};let wu=!1;function bu(e){return function(){const t=this.stateElement;if(!t)return;if(!0!==t.initialized)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 vu(e){return function(t){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[e]=t})}):n.createState("writable",n=>{n[e]=t}))}}function $u(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 xu(e){return e.startsWith("$")}function Su(e,t){return Object.keys(e).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof e[n].value;return"method"===t?o:!o})}function Pu(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||ee(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||ee(`${t} entries must be non-empty strings.`),e.startsWith("$")&&ee(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&ee(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function Iu(e){xl(e);const t=Pu(e,R)??[],n=Pu(e,j)??[],o=Fc(e),s=function(e){const t=e[z];return"object"!=typeof t||null===t?new Set:new Set(Object.keys(t))}(e),r=[];for(const e of t){const t=o[e];if(void 0===t){if(s.has(e)){r.push(e);continue}ee(`${R} entry "${e}" is not declared on the state.${ie(e,Su(o,"value"))}`)}"function"==typeof t.value&&ee(`${R} entry "${e}" is a method. Declare it in ${j} instead.`)}for(const e of n){const t=o[e];void 0===t&&ee(`${j} entry "${e}" is not declared on the state.${ie(e,Su(o,"method"))}`),"function"!=typeof t.value&&ee(`${j} entry "${e}" is not a method. Declare it in ${R} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}function ku(e,t,n){const s=e.tagName.toLowerCase();s.includes("-")||ee(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Ge(e);null!==r&&"function"==typeof r.define||ee(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&ee(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const e of Array.from(t.childNodes))i.content.appendChild(a.importNode(e,!0));const l=t.mode,{bindables:c,commands:d,streamBackedBindables:u}=Iu(n),f=c.length>0||d.length>0?function(e,t,n=[]){const o={protocol:"wc-bindable",version:1,properties:t.map(t=>({name:t,event:`${e}:${t}-changed`,getter:e=>e.target[t]})),inputs:t.map(e=>({name:e}))};if(0===n.length)return o;const s=n.map(e=>({name:e,async:!0}));return{...o,commands:s}}(s,c,d):null,h=c.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(s,c):{},p=o.tagNames.state,g=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=f;static bindableEventMap=h;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(J))return null;this._shadow=this.attachShadow({mode:g.shadowRootMode}),this._shadow.appendChild(g.template.content.cloneNode(!0));const e=Ge(this._shadow);return null!==e&&Je(e,this._shadow),this._shadow}connectedCallback(){const e=this._ensureShadow();if(null!==e&&Object.keys(g.bindableEventMap).length>0){const t=e.querySelector(p);t?(wu||(wu=!0,Cl("dcc",yu)),t.setBindableEventMap(g.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${s}" declares ${R} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},m=Fc(n);for(const[e,t]of Object.entries(m)){if(xu(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=$u(e,o)}else n.get=bu(e),n.set=vu(e);Object.defineProperty(g.prototype,e,n)}for(const e of u)Object.defineProperty(g.prototype,e,{configurable:!0,enumerable:!0,get:bu(e),set:vu(e)});r.define(s,g)}async function Nu(e,t,n){const o=e;try{o.hasAttribute("bind-component")&&ee(`"bind-component" cannot be used inside a [${J}] host. DCC state comes from the template, not from a component property.`);const s=await async function(e,t){try{if(e.hasAttribute("src")){const t=e.getAttribute("src");if(t.endsWith(".js"))return await yl(t);ee(`DCC: Unsupported src type: ${t}`)}const n=e.querySelector('script[type="module"]');if(n)return await ml(n,t.tagName.toLowerCase());ee(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}catch(e){ee(`DCC: Failed to load state: ${e}`)}}(o,t);ku(t,n,s),e.markTreeless(),e.markInitialized(),e.clearConnectedRootNode(),e.settleInitialization()}catch(t){e.failInitializeLoudly(t)}}const _u={order:10,connecting(e){const t=e.parentNode;return t instanceof ShadowRoot&&t.host.hasAttribute(J)?Nu(e,t.host,t):null}};let Au=!1;function Cu(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function Eu(e,t){for(const n of e)if(Cu(t,n.innerSegments))return n;return null}function Mu(e,t){const n=t.slice(e.innerSegments.length);return 0===n.length?e.outerPathInfo.path:e.outerPathInfo.path+l+n.join(l)}const Ou=new Map([["$eq",[0]],["$eqPath",[0,1]],["$eqIndex",[0]],["$dependOn",[0]],["$trackDependency",[0]]]);function Tu(e,t,n){const o=Ou.get(e);return void 0===o?null:(...e)=>{const s=e.slice();for(let e=0;e<o.length;e++){const n=o[e];"string"==typeof s[n]&&(s[n]=t(s[n]))}return n(s)}}const Ru=new WeakMap;function ju(e,t,n){let o=Ru.get(e);void 0===o&&(o=new Map,Ru.set(e,o));const s=o.get(t);null!=s&&ee(`Volume slot "${t}" is already mounted on this tree.`),o.set(t,n)}function Lu(e,t){if(null===e)return!1;const n=Ru.get(e);if(void 0===n||0===n.size)return!1;for(const e of n.keys())if(t===e||t.startsWith(e+l)||e.startsWith(t+l))return!0;return!1}const Wu=new WeakMap;const Du=[];function Bu(e,t,n,o){if(t.length>0){const s=n.split(l),r=Eu(t,s);if(null!==r)return o&&r.readonly&&ee(`[wcs/mount-readonly] volume "${e}" cannot write "${n}": it is injected read-only ("${S}.${r.innerSegments.join(l)}#${m}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${m} from the injection.`),Mu(r,s)}return e+l+n}function zu(e,t,n){let o=-1,s=null;for(const e of t){const t=e.outerPathInfo.path;t.length<=o||(n===t?(o=t.length,s=e.innerSegments.join(l)):n.startsWith(t+l)&&(o=t.length,s=e.innerSegments.join(l)+n.slice(t.length)))}if(e.length>o){if(n===e)return"";if(n.startsWith(e+l))return n.slice(e.length+1)}return s}function Fu(e,t,n=Du){return new Proxy({},{get(o,s){if("string"==typeof s&&"then"!==s){if("$"===s[0]){if("$postUpdate"===s||"$getAll"===s){const o=s;return(s,...r)=>t[o](Bu(e,n,s,!1),...r)}if("$setAll"===s)return(o,...s)=>t.$setAll(Bu(e,n,o,!0),...s);if("$resolve"===s)return(o,...s)=>t.$resolve(Bu(e,n,o,s.length>1),...s);const o=Tu(s,t=>Bu(e,n,t,!1),e=>t[s](...e));return null!==o?o:t[s]}return t[Bu(e,n,s,!1)]}},set:(o,s,r)=>"string"!=typeof s||("$"===s[0]?(t[s]=r,!0):(t[Bu(e,n,s,!0)]=r,!0)),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const qu=new WeakMap,Vu=[];const Hu=new WeakMap,Ku=new WeakSet;function Uu(e){console.error(`[@wcstack/state] volume "${e.mountPath}" was not grafted — the root state element on this root node failed to initialize (its own diagnostic is reported separately). The volume is not at fault: fix the root <wcs-state>.`),e.onGrafted(null)}let Gu=null;let Ju=0;const Xu=["$watch",z,"$scan","$listKeys",M,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],Qu=new Set;function Yu(e,t){const n=e.stateObject[t];if("function"==typeof n)try{const o=e.component[e.stateProp],s=n.call(o);s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)}}function Zu(e,t,n,o,s,r=new Set){0===n.length&&ee(`Cannot build a mount record without host bindings for "${t}".`),xl(s);const i=[],a=new Set;let c=null;for(const e of n){const t=e.propSegments.slice(1),n=t.join(l);a.has(n)&&ee("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo,readonly:!0===e.propModifiers?.includes(m)};i.push(o),0===t.length&&(c=o)}i.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const d=++Ju,u=`#m${d}`,{getterKeys:f,setterKeys:h}=function(e){const t=new Set,n=new Set,o=Fc(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterKeys:t,setterKeys:n}}(s),p=new Set;for(const e of i)1===e.innerSegments.length&&p.add(e.innerSegments[0]);const g={};for(const e of Object.keys(s))e.startsWith("$")||f.has(e)||h.has(e)||"function"!=typeof s[e]&&(r.has(e)||p.has(e)||(g[e]=s[e]));return{id:d,marker:u,component:e,stateProp:t,parentStateElement:o,entries:i,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?u:c.outerPathInfo.path+l+u,stateObject:s,getterKeys:f,setterKeys:h,injectedKeys:r,mappedKeys:p,hasReadonlyEntries:i.some(e=>e.readonly),privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function ef(e){const t=e.indexOf(l);return-1===t?e:e.slice(0,t)}function tf(e,t){const n=Eu(e.entries,t);return null===n?null:Mu(n,t)}function nf(e,t){return e.markerBasePath+l+t}function of(e,t,n,o){let s=e.accessorBySuffixByMarkerParent.get(t);void 0===s&&(s=new Map,e.accessorBySuffixByMarkerParent.set(t,s));const r=t+l+n;s.set(n,{accessorName:o,indexShift:oe(r).wildcardCount-oe(o).wildcardCount}),e.getterKeys.has(o)&&(e.parentStateElement.getterPaths?.add(r),e.addedGetterPaths.add(r))}function sf(e,t){return!e.injectedKeys.has(t)&&(!e.getterKeys.has(t)&&"function"==typeof e.stateObject[t]||!e.mappedKeys.has(t)&&(Object.prototype.hasOwnProperty.call(e.stateObject,t)&&!e.getterKeys.has(t)&&!e.setterKeys.has(t)))}function rf(e,t){return`Path "${t}" in <${e.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${e.entries.filter(e=>e.innerSegments.length>0).map(e=>e.innerSegments.join(l)).join(", ")}). Mount it from the host ("${e.stateProp}: path" / "${e.stateProp}.${ef(t)}: path") or declare the key on the component state.`}const af=/^\$(\d+)$/;function lf(e,t){if(!e.hasReadonlyEntries)return null;const n=t[0];if("$"===n||"#"===n)return null;if(e.getterKeys.has(t)||e.setterKeys.has(t))return null;const o=ef(t);if(e.getterKeys.has(o)||e.setterKeys.has(o)||sf(e,o))return null;const s=function(e,t){return Eu(e.entries,t)}(e,t.split(l));return null!==s&&s.readonly?s:null}function cf(e,t){const n=lf(e,t);if(null!==n){const o=0===n.innerSegments.length?"":l+n.innerSegments.join(l);ee(`[wcs/mount-readonly] <${e.component.tagName.toLowerCase()}> cannot write "${t}": it is mounted read-only ("${e.stateProp}${o}#${m}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${m} from the mount.`)}return df(e,t)}function df(e,t){const n=t[0];if("$"===n||"#"===n)return t;if(e.getterKeys.has(t)||e.setterKeys.has(t))return function(e,t){const n=t.split(l);let o=-1;for(let e=n.length-1;e>=0;e--)if(n[e]===c){o=e;break}if(-1===o)return of(e,e.markerBasePath,t,t),nf(e,t);if(sf(e,n[0]))return of(e,e.markerBasePath,t,t),nf(e,t);const s=n.slice(0,o+1),r=n.slice(o+1),i=tf(e,s);null===i&&ee(rf(e,t)),0===r.length&&ee(`Wildcard-terminal accessor "${t}" on mounted <${e.component.tagName.toLowerCase()}> is not supported: it translates to a marker-terminal path where the mount overlay would shadow the accessor. Declare the row value as a getter on the host tree, or back it with a component-own array (a private key makes the whole path private).`);const a=i+l+e.marker;return of(e,a,r.join(l),t),a+l+r.join(l)}(e,t);const o=ef(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return nf(e,t);if(sf(e,o))return nf(e,t);const s=tf(e,t.split(l));if(null!==s)return s;ee(rf(e,t))}const uf=new Set(["prop","radio","checkbox"]);function ff(e,t,n){let o;const s=af.exec(t.statePathName);if(null!==s){const r=function(e,t){return void 0===t?e.delta:oe(df(e,t)).wildcardCount-oe(t).wildcardCount}(e,n);o=0===r?t.statePathName:`$${Number(s[1])+r}`}else if(o=df(e,t.statePathName),"for"===t.bindingType){const n=oe(o).wildcardCount-t.statePathInfo.wildcardCount;e.indexShiftByLoopElementPath.set(o+l+c,n)}const r=t.propModifiers,i=null===s&&Array.isArray(r)&&uf.has(t.bindingType??"")&&!r.includes(m)&&null!==lf(e,t.statePathName);return o!==t.statePathName||i?{...t,statePathName:o,statePathInfo:oe(o),...i?{propModifiers:[...r,m]}:{}}:t}function hf(e,t,n,o,s){if(void 0===o)return;const r=oe(n).wildcardCount-oe(t).wildcardCount;return 0===r?o:(s.length<r&&ee(`Cannot resolve "${t}" from this mount: the mounted prefix has ${r} wildcard(s) but the host context provides only ${s.length} index(es).`),[...s.slice(0,r),...o])}const pf=new WeakMap,gf=new WeakMap;const mf=new WeakMap;const yf=new FinalizationRegistry(function(e){const t=e.byMarker.get(e.marker);if(void 0!==t&&void 0===t.deref()&&e.byMarker.delete(e.marker),void 0!==e.getterPaths)for(const t of e.addedGetterPaths)e.getterPaths.delete(t)}),wf=new WeakMap;function bf(e){return wf.get(e)??null}let vf=!1;function $f(){vf||(vf=!0,bt=e=>pf.has(e)?e.host:null)}function xf(e){return Sf(e).map(e=>({marker:e.marker,componentTag:e.component.tagName.toLowerCase(),stateProp:e.stateProp,mountTable:e.entries.map(e=>({inner:e.innerSegments.join(l),outer:e.outerPathInfo.path})),delta:e.delta,privateKeys:Object.keys(e.privateSnapshot),getterKeys:[...e.getterKeys],exports:[...e.exports.keys()]}))}function Sf(e){const t=mf.get(e);if(void 0===t)return[];const n=[];for(const e of t.values()){const t=e.deref();void 0!==t&&n.push(t)}return n}function Pf(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=mf.get(e);if(void 0===o)return null;const s=t.indexOf(l,n),r=-1===s?t.slice(n):t.slice(n,s),i=o.get(r);if(void 0===i)return null;const a=i.deref();return void 0===a?(o.delete(r),null):a}const If=new WeakMap,kf=new Set;function Nf(e,t,n,o){let s=If.get(e);if(void 0===s){if(!o)return null;s=new Map,If.set(e,s)}let r=s.get(t);if(void 0===r){if(!o)return null;r=new Map,s.set(t,r)}let i=r.get(n);if(void 0===i){if(!o)return null;i={holders:new Set,byListIndex:new WeakMap,noIndex:null},r.set(n,i)}return i}function _f(e,t){if(!e.component.isConnected)return!1;const n=vt(e.component)?.listIndex??null;if(null===t)return null===n;let o=n;for(;null!==o;){if(o===t)return!0;o=o.parentListIndex}return!1}function Af(e,t,n,o){const s=Nf(e,t,n,!1);if(null===s)return null;const r=null===o?s.noIndex:s.byListIndex.get(o)??null;if(null!==r){const e=function(e,t){const n=e.ref.deref();return void 0!==n&&_f(n,t)?n:null}(r,o);if(null!==e)return{record:e,entry:r.entry}}let i=null,a=null;for(const e of s.holders){const r=e.ref.deref();void 0!==r?_f(r,o)&&(null!==a&&ee(`[wcs/mount-export-ambiguous] "${t}${l}${n}" is exported by two mounted components on the same instance: <${a.component.tagName.toLowerCase()}> and <${r.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),i=e,a=r):s.holders.delete(e)}return null===i||null===a?null:(null===o?s.noIndex=i:s.byListIndex.set(o,i),{record:a,entry:i.entry})}function Cf(e){const t=e.parentStateElement,n=vt(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[Rt](n,()=>{e.$postUpdate(o.exportedPath)})})}const Ef=new WeakMap;class Mf{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(e,t,n,o,s,r){this.record=e,this.markerParentPath=t,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(e){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(e)?.accessorName}accessorAddress(e){return bn(oe(this.markerParentPath+l+e),this.listIndex)}get(e,t,n){if("string"!=typeof t)return Reflect.get(e,t);if("then"===t)return;if("$"===t[0]){if("$postUpdate"===t)return e=>{this.receiver.$postUpdate(df(this.record,e))};if("$getAll"===t||"$setAll"===t||"$resolve"===t){const e=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===t)return(t,s,...r)=>{const i=r.length>0?cf(e,t):df(e,t),a=hf(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const s=t;return(t,r,...i)=>{const a="$setAll"===s?cf(e,t):df(e,t),l=hf(0,t,a,r,n);return o[s](a,l,...i)}}const e=this.record,n=this.receiver,o=Tu(t,t=>df(e,t),e=>n[t](...e));return null!==o?o:this.receiver[t]}const o=this.accessorNameFor(t);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(t));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return Fl(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(n)}return this.receiver[df(this.record,t)]}set(e,t,n,o){if("string"!=typeof t)return Reflect.set(e,t,n);const s=this.accessorNameFor(t);if(void 0!==s){this.record.setterKeys.has(s)||ee(`Cannot write to "${s}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(t)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,s,n,o)}finally{this.handler.endUntrack(),this.handler.popAddress()}}return this.isBase&&Object.prototype.hasOwnProperty.call(e,t)?(e[t]=n,!0):(this.receiver[cf(this.record,t)]=n,!0)}has(e,t){if("string"!=typeof t)return Reflect.has(e,t);if("$"===t[0]||"#"===t[0])return!1;if(void 0!==this.accessorNameFor(t))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return!0;if("function"==typeof this.record.stateObject[t])return!0}try{return df(this.record,t),!0}catch{return!1}}}function Of(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=Ef.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Ef.set(e,n)),null===t)return n.noIndex??={...e.privateSnapshot};let o=n.byListIndex.get(t);return void 0===o&&(o={...e.privateSnapshot},n.byListIndex.set(t,o)),o}(e,t.listIndex):{};return new Proxy(i,new Mf(e,s,t.listIndex,r,n,o))}function Tf(e){const t=e.parentStateElement,n=(t,n)=>{const o=vt(e.component);let s;return t[Rt](o,()=>{s=n()}),s};return new Proxy({},{get(o,s){if("string"!=typeof s||"then"===s)return;if("$getAll"===s||"$setAll"===s||"$resolve"===s||"$postUpdate"===s)return function(e,t,n){const o=e.parentStateElement,s=(e,t)=>{let s;return o.createState(e,e=>{s=n(e,()=>t(e))}),s};return"$postUpdate"===t?t=>s("readonly",n=>n.$postUpdate(df(e,t))):(n,o,...r)=>{const i="$setAll"===t||"$resolve"===t&&r.length>0,a=i?cf(e,n):df(e,n),l=vt(e.component)?.listIndex.indexes??[],c=hf(0,n,a,"$resolve"===t?o??[]:o,l);return s(i?"writable":"readonly",e=>e[t](a,c,...r))}}(e,s,n);const r=Tu(s,t=>df(e,t),e=>{let o;return t.createState("readonly",t=>{o=n(t,()=>t[s](...e))}),o});if(null!==r)return r;let i;return t.createState("readonly",t=>{i=n(t,()=>t["$"===s[0]?s:df(e,s)])}),i},set:(o,s,r)=>("string"!=typeof s||t.createState("writable",t=>{n(t,()=>{t["$"===s[0]?s:cf(e,s)]=r})}),!0),has(t,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(e.stateObject,n))return!0;try{return df(e,n),!0}catch{return!1}}})}function Rf(e,t){const n=function(e){return pf.get(e)??null}(t);var o,s;null!==n&&n.stateProp!==e.stateProp&&ee(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${e.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&ws(t).dispose(),function(e,t){$f(),pf.set(e,t),wf.set(t,e);let n=mf.get(t.parentStateElement);void 0===n&&(n=new Map,mf.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=gf.get(t.component);void 0===o&&(o=new Map,gf.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&yf.register(t,{byMarker:n,marker:t.marker,getterPaths:t.parentStateElement.getterPaths,addedGetterPaths:t.addedGetterPaths}),t.parentStateElement.markHasMounts?.()}(t,e),t instanceof ShadowRoot&&function(e,t){const n=Ca.get(e);if(void 0!==n){if(n===t)return;ee("A state tree is already registered on this root.")}Ca.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>ff(e,t,n);Y(t);const o=vt(e.component);il(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),xa(t,o,n)}(e,t),function(e){if(e.exports.size>0||null===e.rootEntry)return;const t=new Set([...e.getterKeys,...e.setterKeys]);for(const n of t){let t;try{t=df(e,n)}catch{continue}const o=t.indexOf(l+e.marker);if(-1===o)continue;const s=t.slice(0,o+1+e.marker.length),r=t.slice(s.length+1),i=t.slice(0,o)+l+r,a=oe(i);if(a.wildcardCount!==e.delta)continue;const c={markerTerminalPath:s,suffix:r,markerPath:t,exportedPath:i};e.exports.set(i,c),Nf(e.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:c}),e.parentStateElement.addDynamicDependency(t,i),qc?.markExported(e.parentStateElement,i)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=vt(e.component);if(e.delta>0&&null===t)return;const n=e.component.tagName.toLowerCase();for(const o of e.exports.values()){const s=`${n}|${o.exportedPath}`;if(kf.has(s))continue;const r=oe(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Rt](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(kf.add(s),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${e.stateProp}.${o.suffix} is exported at "${o.exportedPath}" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`))}}(e),Cf(e),o=t,s=Promise.resolve(),Ea.set(o,s),s.then(()=>La(o),()=>{})}function jf(e,t){const n=ws(t),o=vt(e.component);n.forEachActiveBindingNode(e=>$t(e,o));va(n.rebindAddresses()),Cf(e)}function Lf(e,t){if(function(e){const t=mf.get(e);return void 0!==t&&t.size>0}(t))for(const n of Sf(t)){if(!Wf(n.component,e))continue;const t=bf(n);null!==t&&jf(n,t)}}function Wf(e,t){for(let n=t.firstNode;null!==n;n=n.nextSibling){if(n===e||n.contains(e))return!0;if(n===t.lastNode)break}return!1}const Df={read(e,t,n,o){if(!0===e.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const s=Pf(e,t.pathInfo.path);if(null!==s)return Of(s,t,n,o)}return Nl},readMissing(e,t,n,o,s){if(null===n){if(Lu(e.rootNode??null,t.pathInfo.path))return;return Nl}if(!0===e.hasMounts){const n=Af(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s){const r=Of(e,bn(oe(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(n.record,n.entry,t.listIndex,o,s)}return Nl},write(e,t){if(!0===e.hasGraftedVolumes){const n=t.pathInfo.path,o=function(e,t){const n=Wu.get(e);if(void 0===n||0===n.size)return null;const o=t+l;for(const e of n)if(e.startsWith(o))return e;return null}(e,n);null!==o&&ee(`Cannot replace "${n}" wholesale: a volume is mounted at "${o}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${o}" itself, or individual fields inside "${n}", instead.`)}return Nl},writeMissing(e,t,n,o,s,r,i){if(!0===e.hasMounts){const n=Af(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s,r){const i=Of(e,bn(oe(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(n.record,n.entry,t.listIndex,s,r,i)}return Nl},indexShift(e,t){const n=e.stateElement,o=t.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const e=Pf(n,o);if(null!==e)return function(e,t){const n=t.lastIndexOf("#");if(-1===n)return e.delta;const o=t.indexOf(l,n);if((-1===o?t.slice(n):t.slice(n,o))!==e.marker)return e.delta;const s=-1===o?t:t.slice(0,o),r=-1===o?"":t.slice(o+1),i=e.accessorBySuffixByMarkerParent.get(s)?.get(r);return void 0!==i?i.indexShift:e.delta}(e,o)}return 0},handlerScope(e,t,n,o,s){if(!0!==e.hasMounts)return s;const r=function(e,t){let n=e;for(;null!==n&&n!==t;){const e=pf.get(n);if(void 0!==e)return e;n=n.parentNode}return pf.get(t)??null}(t,n);if(null===r)return s;const i=r.indexShiftByLoopElementPath.get(o.pathInfo.path);return void 0!==i?s-i:0},updated(e,t,n){const o=function(e){return qu.get(e)??Vu}(e);for(const s of o){const o=new Set,r={};for(const n of t){if(n.absolutePathInfo.stateElement!==e)continue;const t=n.absolutePathInfo.pathInfo.path;if(-1!==t.indexOf("#"))continue;const i=zu(s.mountPath,s.injections,t);if(null===i||""===i)continue;o.add(i);const a=n.absolutePathInfo.pathInfo.wildcardCount;if(a>0&&null!==n.listIndex){const e=on(n.listIndex,a);(r[i]??=[]).push(e)}}if(o.size>0)try{s.callback.call(Fu(s.mountPath,n,s.injections),Array.from(o),r)}catch(e){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,e)}}},suppressPathDiagnostic:(e,t)=>Lu(!1===e.isConnected?null:e.rootNode??null,t),rowReused(e,t){Lf(t,e)}};let Bf=!1;function zf(){Bf||(Bf=!0,Cl("scopes",Df),nd=xf)}const Ff=new WeakMap;function qf(e){let t=Ff.get(e);return void 0===t&&(t={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},Ff.set(e,t)),t}function Vf(e,t){null!==t.slotRootNode&&(!function(e,t,n){const o=Ru.get(e);o?.get(t)===n&&o.set(t,null)}(t.slotRootNode,t.mountPath,e),t.slotRootNode=null)}function Hf(e,t,n){if(t.slotRootNode===n)return!0;const s=t.mountPath;try{ju(n,s,e)}catch{return console.error(`[@wcstack/state] <${o.tagNames.state} mount="${s}"> will not graft: another volume already holds the "${s}" slot on this root. Keep one volume per mount path.`),!1}return Ta(n)?.markHasVolume?.(),t.slotRootNode=n,!0}async function Kf(e,t){const n=e,s=e.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(e){0===e.length&&ee('"mount" requires a non-empty tree path.');const t=oe(e);for(const n of t.segments)0===n.length&&ee(`"mount" path "${e}" has an empty segment.`),n===c&&ee(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&ee(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(r),i=function(e,t){const n=[],s=new Set;let r;try{r=Te(e)}catch(e){ee(`[wcs/mount-path-invalid] <${o.tagNames.state} mount="${t}"> has an invalid ${o.bindAttributeName}: ${e instanceof Error?e.message:String(e)}`)}for(const e of r){if(e.propSegments[0]!==S)continue;const r=e.propSegments.slice(1),i=e.statePathInfo,a=n=>ee(`[wcs/mount-path-invalid] <${o.tagNames.state} mount="${t}"> "${e.propName}: ${e.statePathName}": ${n}`);1===r.length&&r[0]&&r[0]!==c&&"$"!==r[0][0]&&"#"!==r[0][0]||a(`inject one key at a time ("${S}.<key>: path"); change "mount" to move the whole volume.`),(i.wildcardCount>0||"$"===i.path[0]||"#"===i.path[0])&&a("the injected path must be a static path on the root tree (a volume has no loop context)."),(e.inFilters.length>0||e.outFilters.length>0)&&a("an injection takes no filters."),e.propModifiers.some(e=>e!==m)&&a(`an injection accepts only #${m}.`),s.has(r[0])&&a(`"${r[0]}" is injected twice.`),s.add(r[0]),n.push({innerSegments:r,outerPathInfo:i,readonly:e.propModifiers.includes(m)})}return n.sort((e,t)=>t.innerSegments.length-e.innerSegments.length),n}(n.getAttribute(o.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&ee('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),ju(s,r,e),Ta(s)?.markHasVolume?.(),t.mountPath=r,t.slotRootNode=s}catch(t){throw e.settleInitialization(),t}t.initializing=!0,null===Ta(s)&&function(e,t){const n=()=>{if(null!==Ta(e))return;const n=e.querySelectorAll(o.tagNames.state);for(const e of n)if(!e.hasAttribute("mount")&&!e.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${t}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${o.tagNames.state}> to this root node (an empty <${o.tagNames.state}></${o.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},s=e.ownerDocument??e;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(s,r);const a=n=>{t.graftInfo=n,e.markInitialized(),null===n&&Vf(e,t),e.settleInitialization()};let l;try{await Promise.resolve(),l=await e.loadStateFromSource()}catch(e){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,e),void a(null)}const d=e.connectedRootNode??null;null!==d&&Hf(e,t,d)?function(e,t,n,o,s,r,i=[]){const a={mountPath:n,volumeState:o,injections:i,onGrafted:s,acquireSlot:r};if(null!==t)return void $h(t,a);Sh(),function(e,t){if(Ku.has(e))return void Uu(t);let n=Hu.get(e);void 0===n&&(n=[],Hu.set(e,n)),n.push(t)}(e,a)}(d,Ta(d),r,l,a,()=>Hf(e,t,d),i):a(null)}const Uf={order:20,connecting(e){if(!e.hasAttribute("mount"))return null;const t=qf(e);if(t.initializing){const n=e.connectedRootNode;if(null!=n&&t.detachedFrom===n)try{ju(n,t.mountPath,e),Ta(n)?.markHasVolume?.(),t.slotRootNode=n}catch{}return t.detachedFrom=null,jc}return Kf(e,t)},reconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=qf(e),n=e.connectedRootNode??null;return null!==t.graftInfo&&null!==n&&Ta(n)===t.graftInfo.rootStateElement&&wh(t.graftInfo,"$connectedCallback"),!0},replacingState(e){if(!0!==Ff.get(e)?.initializing)return;const t=e.getAttribute("mount");ee(`Cannot replace the state of <${o.tagNames.state} mount="${t}"> after it has loaded: a volume's data is copied into the root tree when it grafts, so a new state would never reach the page. Write the paths under "${t}" on the root state instead.`)},initializeFailed(e,t){!function(e){Ku.add(e);const t=Hu.get(e);if(void 0!==t){Hu.delete(e);for(const e of t)Uu(e)}}(t)},initializeFailureCleared(e,t){!function(e){Ku.delete(e)}(t)},disconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=qf(e);return null!==t.graftInfo&&wh(t.graftInfo,"$disconnectedCallback"),!0!==e.initialized&&(t.detachedFrom=t.slotRootNode,Vf(e,t)),e.clearConnectedRootNode(),!0}};let Gf=!1;const Jf=new WeakMap;function Xf(e,t){let n=Jf.get(e);n||(n=new Set,Jf.set(e,n)),n.add(t)}const Qf=new WeakMap;const Yf=new WeakMap,Zf=new WeakMap;const eh=new WeakMap;const th={isComplete:function(e,t){return!0===Jf.get(e)?.has(t)},isDeclared:function(e,t){return!0===Qf.get(e)?.has(t)},rememberOverwrittenObject:function(e,t,n){let o=Yf.get(e);o||(o=new Map,Yf.set(e,o)),o.has(t)||o.set(t,n)},recordInjectedKey:function(e,t,n){let o=Zf.get(e);o||(o=new Map,Zf.set(e,o));let s=o.get(t);s||(s=new Set,o.set(t,s)),s.add(n)},rememberOverwrittenValue:function(e,t,n,o){let s=eh.get(e);s||(s=new Map,eh.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}};function nh(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)}const oh=new WeakMap;class sh{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=oh.get(e);return n?n.get(t)??null:null}(e,t)??ee("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 rh=e=>()=>e;function ih(e,t,n,o){!function(e,t,n){let o=oh.get(e);o||(o=new Map,oh.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(nh(o));const s=function(e,t){const n=new sh(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:rh(s),enumerable:!0,configurable:!0}),Xf(t,n),ah(t,n)}function ah(e,t){if(T in e){const n=e[T];"function"==typeof n?n.call(e,t).catch(e=>{ee(`Error in ${T}: ${e instanceof Error?e.message:String(e)}`)}):ee(`${T} is not a function.`)}}const lh=new Set;function ch(e,t){lh.has(e)||(lh.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function dh(e){!function(e){const t=e.component.tagName.toLowerCase(),n=e.stateProp;let o=null;for(const s of e.entries){if(0===s.innerSegments.length)continue;const r=s.innerSegments[0];o??=Fc(e.stateObject);const i=o[r];let a;if(e.getterKeys.has(r)||e.setterKeys.has(r)||"function"==typeof i?.get||"function"==typeof i?.set)a="an accessor";else if("function"==typeof i?.value)a="a method";else{if(e.mappedKeys.has(r)||e.injectedKeys.has(r)||!Object.prototype.hasOwnProperty.call(e.stateObject,r))continue;a="an own data key"}const c=s.innerSegments.join(l);ch(`${t}|${n}|${c}|entry`,`<${t}>.${n} declares "${r}" as ${a}, which hides the mounted entry "${n}.${c}: ${s.outerPathInfo.path}" (the host value never reaches it). Rename one of them.`)}}(e);const t=Object.keys(e.privateSnapshot);if(0===t.length)return;const n=e.component.tagName.toLowerCase(),o=e.stateProp;let s,r=!1;for(const i of t){if(null===e.rootEntry)continue;if(r||(s=uh(e),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const t=e.rootEntry.outerPathInfo.path;ch(`${n}|${o}|${i}|root`,`<${n}>.${o}.${i} is private and hides the mounted tree key "${t}.${i}" (${o}: ${t}). Remove the default to read the tree, or rename it to keep it private.`)}}function uh(e){const t=e.rootEntry,n=vt(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[Rt](n,()=>{o=e[t.outerPathInfo.path]})}),o}const fh=new WeakMap;function hh(e,t){e.landInitialization(),ee(t)}async function ph(e,t){const n=e;if(n.hasAttribute("bind-component")){const i=n.parentNode,a=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,l=a?Ke(a):null;null!==a&&null!==l||ee(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(o.bindAttributeName)||hh(e,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const c=["state","src","json"].filter(e=>n.hasAttribute(e));null!==n.querySelector('script[type="module"]')&&c.push('<script type="module">'),c.length>0&&ee(`"bind-component" cannot be combined with ${c.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const d=n.getAttribute("bind-component");!function(e,t){let n=Qf.get(e);n||(n=new Set,Qf.set(e,n)),n.add(t)}(a,d);const u=Ge(a);null===u&&ee(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(o.bindAttributeName)&&await qe(a),d in a||ee(`Component does not have property "${d}" for state binding.`);let f=a[d];"object"==typeof f&&null!==f||ee(`Component property "${d}" is not an object for state binding.`);const h=function(e,t){const n=Yf.get(e);if(!n)return;const o=n.get(t);return n.delete(t),o}(a,d);if(void 0!==h&&function(e,t){if(!e.hasAttribute(o.bindAttributeName))return!1;const n=lt(e);if(null===n)return!1;for(const e of n)if(1===e.propSegments.length&&e.propSegments[0]===t)return!0;return!1}(a,d)&&(a[d]=h,f=h),t.boundComponent=a,t.boundComponentStateProp=d,e.setBoundComponent(a,d),i instanceof ShadowRoot||(lt(a)??[]).some(e=>e.propSegments[0]===d)||hh(e,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${d}: path").`),a.hasAttribute(o.bindAttributeName)){const o=(lt(a)??[]).filter(e=>e.propSegments[0]===d);if(o.length>0){const c=Ta(a.getRootNode())??hh(e,`No state tree found on this root for mount host <${l}>.`);let u=(s=a,r=d,gf.get(s)?.get(r)??null);const h=null!==u;if(null===u&&(!function(e,t,n){const o=eh.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;eh.get(e).delete(t)}}(a,d,f),u=Zu(a,d,o,c,f,function(e,t){return Zf.get(e)?.get(t)}(a,d)),dh(u)),t.mountRecord=u,n.parentNode!==i)return;try{Rf(u,i instanceof ShadowRoot?i:a)}catch(t){throw e.landInitialization(),t}if(!h){const e=Tf(u);Object.defineProperty(a,d,{get:()=>e,enumerable:!0,configurable:!0}),Xf(a,d)}return ah(a,d),function(e){const t=Xu.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(H)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;Qu.has(n)||(Qu.add(n),console.warn(`[@wcstack/state] [wcs/mount-dollar-declaration] <${n.split("|")[0]}>.${e.stateProp} declares ${t.join(", ")}, which mounted components do not run. Declare them on the root state instead (a volume <wcs-state mount="..."> can host $watch / $listKeys / $updatedCallback; $recursion and "**" getters expand against the root tree). See docs/state-mount-design.md §4-6.`))}(u),void Yu(u,"$connectedCallback")}}ih(e,t.boundComponent,t.boundComponentStateProp,f)}var s,r}const gh={order:30,preparing(e){if(!e.hasAttribute("bind-component"))return null;const t=function(e){let t=fh.get(e);return void 0===t&&(t={boundComponent:null,boundComponentStateProp:null,mountRecord:null},fh.set(e,t)),t}(e);return ph(e,t).then(()=>null!==t.mountRecord&&(e.markInitialized(),e.settleInitialization(),!0))},reconnecting(e){const t=fh.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord,o=e.parentNode;return queueMicrotask(()=>{null!=e.connectedRootNode&&jf(n,o)}),Yu(n,"$connectedCallback"),!0},disconnecting(e){const t=fh.get(e);return void 0!==t&&null!==t.mountRecord&&(Yu(t.mountRecord,"$disconnectedCallback"),Cf(t.mountRecord),e.clearConnectedRootNode(),!0)}};let mh=!1;function yh(){mh||(mh=!0,Dc("bindComponent",gh),vs=th)}function wh(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(Fu(e.mountPath,o,e.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function bh(e,t,n,o){const s=n[F];if(void 0!==s){const n=td(t),r=[],i=new Set;let a=0;for(const[n,l]of Object.entries(s)){const s=Bu(t,o,n,!1),c=function(e,n,...s){l.call(Fu(t,this,o),e,n,...s)};r.push({path:s,pathInfo:oe(s),handler:c,order:1e6+a++}),i.add(s),e.setPathInfo(s,"prop","watch")}r.length>0&&(n.addEntries(e,r),e.addVolumeWatchPaths?.(i),n.start(e))}const r=n[K];if(void 0!==r){const n=new Map;for(const[e,s]of Object.entries(r))n.set(Bu(t,o,e,!1),s);e.mergeVolumeListKeys?.(n)}const i=n[M];"function"==typeof i&&(!function(e,t){let n=qu.get(e);void 0===n&&(n=[],qu.set(e,n)),n.push(t),e.markHasVolume?.()}(e,{mountPath:t,injections:o,callback:i}),e.enableUpdatedCallback?.());for(const e of["$commandTokens","$eventTokens","$on","$errorCallback"])void 0!==n[e]&&console.warn(`[@wcstack/state] volume "${t}" declares ${e}, which volumes do not support. Declare it on the root state instead.`)}function vh(e,t,n,o=[]){xl(n),function(e,t,n,o){const s=0===o.length?null:Fc(n);for(const e of o){const n=e.innerSegments[0],o=s[n];void 0===o||"function"!=typeof o.get&&"function"!=typeof o.set&&"function"!=typeof o.value||ee(`[wcs/mount-path-invalid] Volume "${t}" declares "${n}" as an accessor or a method and also injects it ("${S}.${n}: ${e.outerPathInfo.path}"). Rename one of them.`)}const r=n[F];if(void 0!==r){"object"==typeof r&&null!==r||ee(`${F} must be an object mapping state paths to handler functions.`);const e=td(t);for(const[t,n]of Object.entries(r))"function"!=typeof n&&ee(`${F} entry "${t}" must be a function.`),e.assertValidPath(t)}const i=n[K];if(void 0!==i){"object"==typeof i&&null!==i||ee(`${K} must be an object mapping list paths to key specs.`);for(const[n,s]of Object.entries(i)){(0===n.length||"string"!=typeof s&&"function"!=typeof s)&&ee(`${K} entry "${n}" must map a list path to a field name or a key function.`);const r=Bu(t,o,n,!1);e.listKeys?.has(r)&&ee(`${K} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[z]&&ee(`Volume "${t}" declares ${z}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&ee(`Volume "${t}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[V]&&ee(`Volume "${t}" declares ${V}, which volumes do not support yet. Declare the recursion anchor on the root state — the anchor path is resolved against the root tree.`);for(const e of Object.keys(Fc(n)))-1!==e.indexOf(H)&&ee(`Volume "${t}" declares "${e}", which uses "${H}". Volumes do not support recursive getters yet — declare them on the root state.`)}(e,t,n,o);const{data:s,accessors:r}=function(e,t){const n={},o=new Map;for(const[s,r]of Object.entries(Fc(e)))s.startsWith("$")||t.has(s)||("function"!=typeof r.get&&"function"!=typeof r.set?"function"!=typeof r.value&&(n[s]=r.value):o.set(s,r));return{data:n,accessors:o}}(n,new Set(o.map(e=>e.innerSegments[0]))),i=oe(t),a=!0===e.hydratedFromSsr;e.createState("writable",e=>{if(1===i.segments.length&&t in e){if(a)return;ee(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let t=0;t<i.segments.length-1;t++){const o=i.segments[t],s=""===n?o in e:void 0!==e[n+l+o];n=""===n?o:n+l+o,s||(e[n]={})}if(i.segments.length>1&&void 0!==e[t]){if(a)return;ee(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}e[t]=s}),function(e,t){let n=Wu.get(e);void 0===n&&(n=new Set,Wu.set(e,n)),n.add(t)}(e,t),e.markHasGraftedVolumes?.();for(const[n,s]of r){const r=t+l+n,i=s.get,a=s.set,c={enumerable:!1,configurable:!0};"function"==typeof i&&(c.get=function(){return i.call(Fu(t,this,o))}),"function"==typeof a&&(c.set=function(e){a.call(Fu(t,this,o),e)}),e.defineTreeAccessor(r,c)}bh(e,t,n,o);const c=n.$connectedCallback;return"function"==typeof c&&e.createState("writable",e=>{let n;try{n=c.call(Fu(t,e,o))}catch(e){return void console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)}n instanceof Promise&&n.catch(e=>{console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)})}),{rootStateElement:e,mountPath:t,volumeState:n,injections:o}}function $h(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=vh(e,t.mountPath,t.volumeState,t.injections)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" failed to graft.`,e)}finally{t.onGrafted(n)}}let xh=!1;function Sh(){var e;xh||(xh=!0,zf(),Gf||(Gf=!0,Dc("scopes",Uf)),yh(),Gu=$h,e=Ph,Oa.includes(e)||Oa.push(e))}function Ph(e,t){(function(e){const t=Ru.get(e);return void 0!==t&&t.size>0})(e)&&t.markHasVolume?.(),function(e,t){Ku.delete(e);const n=Hu.get(e);if(void 0===n||0===n.length||null===Gu)return;Hu.delete(e);const o=Gu;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,t)}const Ih={name:"scopes",install(){Sh(),Au||(Au=!0,Dc("dcc",_u))}},kh=/^@@wcs-(?:for|if|elseif|else):[^-]/,Nh=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,_h=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,Ah=/^@@wcs-text-start:(.+)$/;function Ch(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function Eh(e,t){const n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();){const e=n.currentNode;t(e.data)&&o.push(e)}return o}const Mh=e=>kh.test(e),Oh=e=>Nh.test(e);function Th(e){const t=e.fragment.cloneNode(!0);for(const n of e.nodeInfos){const o=Za(st(e.fragment,n.nodePath));if(null===o)continue;const s=st(t,n.nodePath);s.parentNode.replaceChild(document.createComment(o),s)}return t}class Rh extends zc{_stateData=null;_templates=null;_hydrateProps=null;get version(){return this.getAttribute("version")||""}get stateData(){return null===this._stateData&&(this._stateData=this._loadStateData()),this._stateData}get templates(){return null===this._templates&&(this._templates=this._loadTemplates()),this._templates}get hydrateProps(){return null===this._hydrateProps&&(this._hydrateProps=this._loadHydrateProps()),this._hydrateProps}getTemplate(e){return this.templates.get(e)??null}verifyVersion(){const e=this.version;if(!e)return!0;const t=e.split("."),n=sd.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 find(e){const t=o.tagNames.ssr,n=e instanceof Element?e:e instanceof Document?e.documentElement:null;if(!n)return null;return n.querySelector(t)}static extractStateData(e){const t=e.__state;if(!t||"object"!=typeof t)return{};const n={};for(const e of Object.keys(t)){if(e.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(t,e);if(void 0!==o&&"function"==typeof o.get)continue;const s=t[e];"function"!=typeof s&&(n[e]=s)}return n}static buildContent(e,t,n){const s=n??e.ownerDocument,r=document.createElement("script");r.setAttribute("type","application/json"),r.textContent=Ch(JSON.stringify(t)),e.appendChild(r);for(const[t,n]of function(e){const t=new Map,n=[e];for(;n.length>0;)for(const e of Eh(n.shift(),Mh)){const o=e.data,s=o.slice(o.indexOf(":")+1);if(t.has(s))continue;const r=za(s);null!==r&&(t.set(s,r),n.push(r.fragment))}return t}(s)){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),s.content.appendChild(Th(n)),e.appendChild(s)}const i=e.ownerDocument,a=Array.from(zi);if(a.length>0){const t={};for(let e=0;e<a.length;e++){const n=a[e];if(!n.isConnected||n.ownerDocument!==i)continue;const o=Bi(n);if(0===o.length)continue;const s=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",s);const r={};for(const e of o)r[e.propName]=e.value;t[s]=r}if(Object.keys(t).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=Ch(JSON.stringify(t)),e.appendChild(n)}}Fi()}static removeBlockBoundaryComments(e){for(const t of Eh(e,e=>Nh.test(e)||_h.test(e)))t.remove()}static removeStructuralComments(e){for(const t of Eh(e,Mh))t.remove()}static restoreTextBindings(e){for(const t of Eh(e,e=>Ah.test(e))){const e=Ah.exec(t.data)[1],n=document.createComment(`@@: ${e}`);t.parentNode.insertBefore(n,t);let o=t.nextSibling;t.remove();const s=`@@wcs-text-end:${e}`;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)}}for(const e of Eh(t,Oh)){const t=Nh.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()}Rh.restoreTextBindings(t);for(const e of Eh(t,Mh)){const t=s.get(e.data.split(":")[1]);if(t){const n=document.createElement("template"),s=t.getAttribute(o.bindAttributeName);s&&n.setAttribute(o.bindAttributeName,s);const r=document.importNode(t.content,!0);if(r.childNodes.length>0)n.content.appendChild(r);else for(const e of Array.from(t.childNodes))n.content.appendChild(document.importNode(e,!0));e.parentNode.replaceChild(n,e)}}const r=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of r)e.removeAttribute("data-wcs-ssr-id");for(const e of n)e.remove()}}const jh={protocol:"wcs-ssr-snapshot",version:1,build:function(e){const t=o.tagNames.state,n=o.tagNames.ssr,s=e.querySelectorAll(`${t}[enable-ssr]:not([mount]):not([bind-component])`);for(const e of s){const t=e.previousElementSibling;if(null!==t&&t.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",sd),Rh.buildContent(o,Rh.extractStateData(e),e.getRootNode()),e.parentNode?.insertBefore(o,e)}Fi()},reset:function(){Da.clear(),Fi()}};const Lh=new Set(["for","if","elseif","else"]);function Wh(e){const t=new ys;if(0===e.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:t,deferredSpreads:[]};const n=e[0].parentNode,o=e[e.length-1].nextSibling,s=document.createElement("div");for(const t of e)s.appendChild(t);const[r,i,a]=gt(s),l=t.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:l,subscriberNodes:r,bindingSession:t,deferredSpreads:a}}const Dh=/^\s*@@\s*(?:wcs-text)?\s*:/;function Bh(e,t,n){for(const o of t)"event"===o.bindingType||Lh.has(o.bindingType)||(o.node.nodeType!==Node.COMMENT_NODE||"text"===o.bindingType&&Dh.test(o.node.data))&&(o.statePathName in A||oe(o.statePathName).wildcardCount>n||e.push(o))}function zh(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}`;return Eh(e,e=>e===r)[0]??null}function Fh(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,Va()],bindingType:"else"}),"if"===i||"elseif"===i?s=t:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?t.statePathName:void 0;tl(a),"string"==typeof l&&Xa(a,l),il(n,a,l);Ba(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:el(a)})}}const qh={hydrate:async function(e){await Pa(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="${sd}". Falling back to full render.`),Rh.cleanupDom(e),!1}for(const n of t)Fh(e,n);Rh.restoreTextBindings(document.body);const n=function(e){const t=[];for(const n of Eh(e,Oh)){const e=Nh.exec(n.data),o=e[1],s=e[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=n.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),s=function(e,t){const n=new Map,o=[];for(const s of t){if(0===s.nodes.length)continue;const t=wi(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a,deferredSpreads:l}=Wh(s.nodes);Yr(t,a);for(const e of i)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");ks(t,r),ti(t,i);const d=[];for(const e of r)e.statePathName in A&&d.push(e);if(As(t,d),"for"===s.type&&null!==s.index){const i=zh(e,"for",s.uuid);if(i){const e=js(null,s.index);Ai(i,e,t),Ci(i,s.nodes[s.nodes.length-1]),fi(i,t);const d=oe(s.path+"."+c),u=bn(d,e);ni(t,u),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Bh(o,r,d.wildcardCount),$a(l,u,a);let f=n.get(s.uuid);f||(f=[],n.set(s.uuid,f)),f.push(e)}}else{const n=zh(e,s.type,s.uuid);n&&(fi(n,t),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Bh(o,r,0),$a(l,null,a))}}for(const[t,o]of n){const n=zh(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=za(t);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=Ta(s);a&&a.createState("readonly",e=>{const t=e[i];Array.isArray(t)&&Us(t,o)})}return o}(document.body,n);Rh.removeBlockBoundaryComments(document.body);const r=[];for(const e of t)e.parentNode&&(r.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());const[i,a,l]=gt(document.body);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||($t(e,null),t.setAttribute("data-wcs-completed",""))}else $t(e,null);const d=[],u=[],f=ws(document.body),h=f.initialize(a);$a(l,null,f);for(const e of h)if("event"!==e.bindingType)if(Lh.has(e.bindingType))u.push(e);else{if(e.statePathName.includes(c))continue;d.push(e)}for(const e of u)if("for"===e.bindingType){const t=cn(e),n=Ta(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&(It(t,o),Et(t,o))})}va([...d,...s]);for(const{el:e,parent:t,next:n}of r)t.insertBefore(e,n);const p=new Map;for(const t of e.querySelectorAll("[data-wcs-ssr-id]"))p.set(t.getAttribute("data-wcs-ssr-id"),t);for(const t of e.querySelectorAll(o.tagNames.ssr))for(const[e,n]of Object.entries(t.hydrateProps)){const t=p.get(e);if(t)for(const[e,o]of Object.entries(n))t[e]=o}for(const t of e.querySelectorAll("[data-wcs-completed],[data-wcs-ssr-id]"))t.removeAttribute("data-wcs-completed"),t.removeAttribute("data-wcs-ssr-id");return!0},loadState(e){const t=e.parentNode;if(!t)return null;const n=Rh.find(t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(e){await Ra(e.rootNode);const t=Rh.extractStateData(e),n=document.createElement(o.tagNames.ssr);n.setAttribute("version",sd),Rh.buildContent(n,t,e.rootNode),e.parentNode?.insertBefore(n,e)}};let Vh=!1;function Hh(){Vh||(Vh=!0,_a=qh,function(e){if(!Gc.includes(e)){Gc.push(e);for(const t of Xc())e(t)}}(e=>{e.get(o.tagNames.ssr)||e.define(o.tagNames.ssr,Rh)}),function(){const t=globalThis;void 0===t[e]&&(t[e]=jh)}())}const Kh={name:"ssr",install(){Hh()}},Uh=new WeakMap,Gh=new Set,Jh=new Set;function Xh(e){return e.byFromPath.size>0||e.byResetPath.size>0}function Qh(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function Yh(e){return Uh.get(e)}function Zh(e){ep(e),Uh.delete(e)}function ep(e){Gh.delete(e),Jh.delete(e)}const tp=new WeakSet;let np=0;function op(e){return Yh(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function sp(e){if(0===Jh.size)return;if(t=e.absolutePathInfo.stateElement,!Jh.has(t))return;var t;const n=op(e);if(void 0!==n)for(const e of n)rp(e)}function rp(e){tp.has(e)||(tp.add(e),np++)}function ip(e){return!!tp.delete(e)&&(np--,!0)}const ap=/^(?:0|[1-9]\d*)$/;function lp(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function cp(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return null;const t=Object.getPrototypeOf(e);if(Array.isArray(e)){return t===Array.prototype&&Reflect.ownKeys(e).every(t=>"length"===t||"string"==typeof t&&ap.test(t)&&lp(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&lp(e,t))?"object":null}function dp(e,t){const n=cp(e);if(null===n)return e;const o=e,s=t.get(o);if(void 0!==s)return s;let r;r="array"===n?new Array(e.length):null===Object.getPrototypeOf(e)?Object.create(null):{},t.set(o,r);for(const e of Object.keys(o))r[e]=dp(o[e],t);return r}function up(e){return dp(e,new Map)}function fp(e,t,n){if(Object.is(e,t))return!0;const o=cp(t);if(null===o||"object"!=typeof e||null===e)return!1;const s=e,r=t;if("array"===o){if(!Array.isArray(e)||e.length!==t.length)return!1}else if(Array.isArray(e)||Object.keys(s).length!==Object.keys(r).length)return!1;if(cp(e)!==o)return!1;let i=n.get(s);if(void 0===i)i=new Set,n.set(s,i);else if(i.has(r))return!0;if(i.add(r),"array"===o){for(let t=0;t<e.length;t++)if(!fp(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&fp(s[e],r[e],n))}function hp(e,t){return fp(e,t,new Map)}const pp=new WeakMap;function gp(e,t){if("function"!=typeof t)return;const n=pp.get(t);void 0===n?pp.set(t,new Set([e])):n.add(e)}function mp(e,t){return"function"==typeof t&&!0===pp.get(t)?.has(e)}const yp={"read-source":e=>`${q} could not read a "from" value for "${e}". That landing was not folded; the other landings of the batch still were.`,"read-rows":e=>`${q} could not read the rows of "from" for "${e}". Nothing was folded or written.`,"read-output":e=>`${q} could not read the output "${e}". Nothing was folded or written.`,threw:e=>`${q} fold for "${e}" threw. The output was not written.`,"returned-promise":e=>`${q} fold for "${e}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:e=>`${q} could not write the output "${e}".`},wp={"read-source":"evaluate","read-rows":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function bp(e,t,n){null!==xt&&xt({type:"state:watch-error",phase:t,path:`${q}.${e}`,error:n})}function vp(e,t,n){console.error(`[@wcstack/state] ${yp[n](e)}`,t),bp(e,wp[n],t)}function $p(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function xp(e,t){t.then(void 0,()=>{}),vp(e,new TypeError(`${q} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const Sp=new WeakSet;const Pp="[wcs/scan-declaration-invalid]",Ip=Object.freeze([]);function kp(e){return`${q} entry "${e}"`}function Np(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function _p(e,t,n,o){return`[wcs/scan-source-computed] ${e} ${t} "${n}" ${o===n?"is a getter":o.includes(`${c}${c}`)?`is computed by the recursive getter "${o}"`:`is under the getter "${o}"`}. A getter re-evaluates whenever its inputs change, so folding it would count re-evaluations, not events. Fold the plain value the getter reads, or use "on" with an event token.${ae}`}function Ap(e,t,n){0===n.length&&ee(`${Pp} ${e} "${t}" must be a non-empty state path.${ae}`),n.startsWith("$")&&ee(`${Pp} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${ae}`),n.includes("@")&&ee(`${Pp} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${ae}`),n in Object.prototype&&ee(`${Pp} ${e} ${t} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ae}`);const o=oe(n);for(const s of o.segments)0===s.length&&ee(`${Pp} ${e} ${t} "${n}" has an empty path segment.${ae}`);return o.wildcardCount>d&&ee(`${Pp} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function Cp(e,t,n,o){const s=kp(e);0===e.length&&ee(`${Pp} ${q} entry name must be a non-empty string.${ae}`),(e.includes(l)||e.includes(c))&&ee(`${Pp} ${s} must be a flat property name ("${l}" and "${c}" are not allowed). The output is a property the runtime owns.${ae}`),e.startsWith("$")&&ee(`${Pp} ${s} must not start with "$" (reserved namespace).${ae}`),e in Object.prototype&&ee(`${Pp} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ae}`),t.has(e)&&ee(`${Pp} ${s} conflicts with a getter declared on the state.${ae}`),n.has(e)&&ee(`${Pp} ${s} conflicts with a setter declared on the state.${ae}`),o.has(e)&&ee(`${Pp} ${s} conflicts with the ${z} entry of the same name — each output has exactly one owner.${ae}`)}function Ep(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!mp(e,o)&&ee(`${Pp} ${kp(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${ae}`)}function Mp(e,t,n,o,s,r){const i=kp(e),a=void 0!==t.from,c=void 0!==t.on;if(a===c&&ee(`${Pp} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${ae}`),c){const e=t.on;return"string"==typeof e&&0!==e.length||ee(`${Pp} ${i} "on" must be a non-empty event-token name.${ae}`),n.has(e)||ee(`${Pp} ${i} on "${e}" is not declared in ${D}.${ie(e,n)}${ae}`),{kind:"event",tokenName:e}}const d=t.from;"string"!=typeof d&&ee(`${Pp} ${i} "from" must be a state path string.${ae}`);const u=Ap(i,"from",d),f=Np(u,o)??r?.recursiveGetterOwning(d)??null;null!==f&&ee(_p(i,"from",d,f));const h=Np(u,s);return null!==h&&ee(function(e,t,n){return`${Pp} ${e} from "${t}" ${n===t?"is a setter without a getter":`is under the setter without a getter "${n}"`}, so it always reads undefined and every fold would receive undefined. Fold the plain value the setter writes, or use "on" with an event token.${ae}`}(i,d,h)),(d===e||d.startsWith(e+l))&&ee(`${Pp} ${i} from "${d}" reads the entry's own output — the scan would fold its own writes forever.${ae}`),{kind:"path",path:d,pathInfo:u}}function Op(e,t,n,o){if(void 0===t)return Ip;const s=kp(e);Array.isArray(t)||ee(`${Pp} ${s} "resetOn" must be an array of state paths.${ae}`);const r=[];for(const e of t){"string"!=typeof e&&ee(`${Pp} ${s} "resetOn" must contain only state path strings.${ae}`);const t=Ap(s,"resetOn",e);t.wildcardCount>0&&ee(`${Pp} ${s} resetOn "${e}" must not contain "${c}" — a reset returns the whole output to "initial".${ae}`);const i=Np(t,o);null!==i&&ee(_p(s,"resetOn",e,i)),"path"===n.kind&&e===n.path&&ee(`${Pp} ${s} resetOn "${e}" is the entry's own "from" — every change would reset instead of fold.${ae}`),"path"===n.kind&&e.startsWith(n.path+l)&&ee(`${Pp} ${s} resetOn "${e}" sits under the entry's own "from" "${n.path}" — every write of "from" also lands it, so the reset would win every time and nothing would fold.${ae}`),r.push(e)}return r}function Tp(e,t,n=null){const o=e[q];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&ee(`${Pp} ${q} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${ae}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[t,n]of Object.entries(Fc(e)))"function"==typeof n.get?s.add(t):"function"==typeof n.set&&i.add(t),"function"==typeof n.set&&r.add(t),"function"==typeof n.value&&a.set(t,n.value);const l=function(e){xl(e);const t=e[z];return"object"!=typeof t||null===t?new Set:new Set(Object.keys(t))}(e),c=[];let d=0;for(const[e,u]of Object.entries(o)){Cp(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&ee(`${Pp} ${kp(e)} must be an object ({ from | on, initial, fold, resetOn? }).${ae}`);const o=u;Ep(e,a,o);const f=Mp(e,o,t,s,i,n);"initial"in o||ee(`${Pp} ${kp(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${ae}`),"function"!=typeof o.fold&&ee(`${Pp} ${kp(e)} fold must be a function.${ae}`);const h=Op(e,o.resetOn,f,s);c.push({name:e,source:f,fold:o.fold,initial:o.initial,resetOn:h,order:d++})}return function(e){const t=new Set(e.map(e=>e.name)),n=new Map;for(const o of e){for(const e of o.resetOn){const n=oe(e).segments[0];t.has(n)&&ee(`${Pp} ${kp(o.name)} resetOn "${e}" reads the ${q} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${ae}`)}if("path"===o.source.kind){const e=o.source.pathInfo.segments[0];t.has(e)&&n.set(o.name,e)}}for(const e of n.keys()){const o=[e];let s=n.get(e);for(;void 0!==s&&o.length<=t.size;)s===e&&ee(`${Pp} ${q} entries ${[...o,e].map(e=>`"${e}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${ae}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}function Rp(e){const t=e.fold;return(n,o,...s)=>{const r=n;let i="read-output";try{const n=r[e.name];i="threw";const a=function(e){return tp.has(e)}(e),l=a&&!hp(n,e.initial)?up(e.initial):n,c=t(l,o,...s);if($p(c))return void xp(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,gp(e.name,c)),a&&ip(e)}catch(t){vp(e.name,t,i)}}}function jp(e,t,n){const o=function(e,t){Zh(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&Qh(n,e.source.path,e);for(const t of e.resetOn)Qh(o,t,e),"event"===e.source.kind&&Qh(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return Uh.set(e,r),r}(e,t);for(const o of t){const t=n.get(o.name);"event"===o.source.kind&&void 0!==t&&(o.resetOn.some(n=>t.includes(n)&&ar().hasQueuedPath(e,n))&&rp(o))}const s=new Set;for(const t of o.byFromPath.keys())s.add(t),e.setPathInfo(t,"prop","scan");for(const t of o.byResetPath.keys())e.setPathInfo(t,"prop","scan");return s.size>0?s:null}const Lp="scanEntries",Wp={order:8,validate(e,t,n){const o=Tp(t,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Lp,o)},applyEarly(e,t,n){const o=n.get(Lp)??null;null!==o&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=up(n.initial);e[n.name]=t,gp(n.name,t)}}(t,o),function(e,t){for(const n of t)"event"===n.source.kind&&Rn(e,n.source.tokenName).subscribe(Rp(n))}(e,o))},register(e,t,n){const o=n.get(Lp)??null,s=function(e){const t=new Map,n=Yh(e);if(void 0!==n)for(const e of n.entries)ip(e)&&t.set(e.name,e.resetOn);return Zh(e),t}(e);e.setScanPaths?.(null===o?null:jp(e,o,s))}};let Dp=!1;const Bp=Object.freeze([]),zp=Object.freeze([]);function Fp(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??Bp,i=e.dynamicDependency.get(n)??Bp,a=t.byFromPath.get(n)??zp;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}const qp=Symbol("wcs-stream-last-notified-uncertain"),Vp=new WeakMap;function Hp(e,t){const n=Vp.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function Kp(e,t){const n=Vp.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:qp,error:Object.is(o.error,null)?null:qp})}const Up=new Set;function Gp(e){Up.delete(e)}const Jp=new WeakMap;function Xp(e){return Jp.get(e)??new Map}function Qp(e){Gp(e);const t=Jp.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Kp(e,n.name)}const Yp=(e,t)=>t,Zp=new Set;function eg(e,t){xl(t);const n=t[z];if(void 0===n)return void Hp(e,Zp);"object"==typeof n&&null!==n||ee(`${z} must be an object mapping stream names to stream definitions.`);const o=new Map,s=Fc(t);for(const[r,i]of Object.entries(n)){0===r.length&&ee(`${z} entry name must be a non-empty string.`),r.includes(l)&&ee(`${z} entry "${r}" must be a flat property name ("${l}" is not allowed).`),r.includes(c)&&ee(`${z} entry "${r}" must be a flat property name ("${c}" is not allowed).`),r.startsWith("$")&&ee(`${z} entry "${r}" must not start with "$" (reserved namespace).`),r in Object.prototype&&ee(`${z} entry "${r}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(r)&&ee(`${z} entry "${r}" conflicts with a getter declared on the state.`),e.setterPaths.has(r)&&ee(`${z} entry "${r}" conflicts with a setter declared on the state.`),"object"==typeof i&&null!==i||ee(`${z} entry "${r}" must be an object ({ args?, source, fold?, initial? }).`);const n=i,a=s[r]?.value;"function"!=typeof a||a===n.initial||mp(r,a)||ee(`${z} entry "${r}" conflicts with a method (a function-valued property) declared on the state. The value is a property the runtime owns.`),"function"!=typeof n.source&&ee(`${z} entry "${r}" source must be a function.`);const d=void 0!==n.fold;d&&"function"!=typeof n.fold&&ee(`${z} entry "${r}" fold must be a function.`),d&&!("initial"in n)&&ee(`${z} entry "${r}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&ee(`${z} entry "${r}" args must be a function.`);const u={name:r,definition:{args:n.args??null,source:n.source,fold:n.fold??Yp,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};r in t||(t[r]=u.definition.initial,gp(r,u.definition.initial)),o.set(r,u)}!function(e,t){Jp.set(e,t)}(e,o),Hp(e,new Set(o.keys()))}const tg=new WeakMap,ng=new WeakMap;function og(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=Xp(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&Xp(e).has(n),ownKeys:()=>Array.from(Xp(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=Xp(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){ee(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){ee(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function sg(e){const t=tg.get(e);if(void 0!==t)return t;const n=og(e,U,e=>e.status);return tg.set(e,n),n}function rg(e){const t=ng.get(e);if(void 0!==t)return t;const n=og(e,G,e=>e.error);return ng.set(e,n),n}function ig(e){tg.delete(e),ng.delete(e)}let ag=null;function lg(e,t){let n=e;for(let e=1;e<t.length;e++){if(Object(n)!==n)return;n=Reflect.get(n,t[e])}return n}const cg={read(e,t){!function(e,t){null!==ag&&ag.add(Jt(e,t))}(e,t);const n=t.pathInfo.segments[0];return n===U?lg(sg(e),t.pathInfo.segments):n===G?lg(rg(e),t.pathInfo.segments):Nl},get:(e,t)=>t===U?sg(e.stateElement):t===G?rg(e.stateElement):Nl};async function dg(e,t,n,o){let s=null;const r=()=>{if(null!==s)try{s.return?.()?.then?.(void 0,()=>{})}catch{}};n.addEventListener("abort",r,{once:!0});try{const i=await e(t,n);if(s=function(e,t){if("function"==typeof e?.getReader)return async function*(e,t){const n=e.getReader(),o=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",o,{once:!0});try{for(;;){const{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t.removeEventListener("abort",o),n.releaseLock()}}(e,t);if("function"==typeof e?.[Symbol.asyncIterator])return e;throw new TypeError(`[@wcstack/state] ${z}: source must return an AsyncIterable or a ReadableStream (got neither).`)}(i,n)[Symbol.asyncIterator](),n.aborted)return void r();for(;;){const e=await s.next();if(e.done)break;if(n.aborted)return;o.fold(e.value)}if(n.aborted)return;o.done()}catch(e){if(n.aborted)return;o.fail(e)}finally{n.removeEventListener("abort",r)}}function ug(e){wg();const t=Xp(e);if(0!==t.size){!function(e){Up.add(e)}(e);for(const n of t.values())fg(e,n)}}function fg(e,t){t.controller?.abort();const n=new AbortController;t.controller=n;const o=function(e,t){const n=t.definition.args;if(null===n)return void t.depAddresses.clear();const o=ag,s=new Set;let r;ag=s;try{e.createState("readonly",e=>{r=n(e)})}finally{ag=o}r instanceof Promise&&ee(`${z} entry "${t.name}" args must be synchronous (it returned a Promise).`);const i=`${U}${l}${t.name}`,a=`${G}${l}${t.name}`;for(const n of s){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==e||o.path!==t.name&&o.path!==i&&o.path!==a||ee(`${z} entry "${t.name}" args must not read the stream itself ("${o.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),o.wildcardCount>0&&ee(`${z} entry "${t.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return t.depAddresses=s,r}(e,t);!function(e,t){const n=Yh(e);if(void 0!==n&&0!==t.depAddresses.size)for(const o of n.entries){if("path"!==o.source.kind||o.source.pathInfo.segments[0]!==t.name)continue;const s=Fp(e,n,o.name);for(const e of t.depAddresses){const n=e.absolutePathInfo.pathInfo.path;s.has(n)&&ee(`[wcs/scan-feedback-loop] ${z} entry "${t.name}" args read "${n}", which is derived from the ${q} output "${o.name}" that this stream feeds. Every landing would restart the stream on its own result. Advance the cursor from an event ($on) and keep it a plain property instead of deriving it from the accumulator.`)}}}(e,t),e.createState("writable",e=>{e[t.name]=t.definition.initial}),gp(t.name,t.definition.initial),hg(e,t,"active",null);const s=t.definition,r={fold(n){e.createState("writable",e=>{const o=s.fold(e[t.name],n);e[t.name]=o,gp(t.name,o)})},done(){hg(e,t,"done",null)},fail(o){hg(e,t,"error",o),n.abort()}};dg(s.source,o,n.signal,r)}function hg(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return Vp.get(e)?.get(t)??{status:"idle",error:null}}(e,t.name),r=s.status!==n,i=!Object.is(s.error,o);(r||i)&&(!function(e,t,n,o){let s=Vp.get(e);void 0===s&&(s=new Map,Vp.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{r&&e.$postUpdate(`${U}${l}${t.name}`),i&&e.$postUpdate(`${G}${l}${t.name}`)}))}function pg(e){const t=Up;if(0===t.size)return;const n=[];for(const o of t)for(const t of Xp(o).values())for(const s of t.depAddresses)if(e.has(s)){n.push({stateElement:o,entry:t});break}for(const{stateElement:e,entry:o}of n)if(t.has(e)&&Xp(e).get(o.name)===o)try{fg(e,o)}catch(n){o.controller?.abort(),t.has(e)&&Xp(e).get(o.name)===o&&hg(e,o,"error",n)}}let gg=!1;const mg=new WeakMap,yg={order:20,apply(e,t){var n;ig(e),Qp(n=e),Gp(n),Jp.delete(n),eg(e,t),void 0!==t[z]&&e.attachAddressHooks?.("streams",z)},activate(e,n){if(!t()&&null!=e.connectedRootNode){if(null===n){if(!0!==e.initialized)return;return ug(e),void mg.set(e,e.connectGeneration??0)}n===e.connectGeneration&&mg.get(e)!==n&&ug(e)}},deactivate(e){Qp(e),ig(e)}};function wg(){gg||(gg=!0,Cl("streams",cg),Tl("streams",yg),or(pg,20))}let bg=0,vg=0;function $g(e){bg=e+1}function xg(){bg=0}function Sg(){bg>vg&&(vg=bg)}const Pg=new WeakMap;function Ig(e,t,n){let o=Pg.get(e);void 0===o&&(o=new Map,Pg.set(e,o)),o.set(t,n)}const kg=new Map;function Ng(e,t){kg.has(e)||kg.set(e,t)}function _g(e){return kg.get(e)}const Ag=new WeakMap,Cg=new WeakMap,Eg=new Set,Mg=new Map;function Og(e){return Ag.get(e)??Mg}function Tg(e){Eg.add(e),function(e){const t=Uh.get(e);void 0!==t&&(Xh(t)&&Gh.add(e),function(e){return e.eventResetByPath.size>0}(t)&&Jh.add(e))}(e)}function Rg(){return Eg}function jg(e,t){let n=Cg.get(e);void 0===n&&(n=new Map,Cg.set(e,n));for(const e of t){const t=n.get(e.path);void 0===t?n.set(e.path,[e]):t.push(e)}}const Lg=new Map;function Wg(e){return Cg.get(e)??Lg}function Dg(e){0===e.length&&ee(`[wcs/watch-declaration-invalid] ${F} entry name must be a non-empty state path.`),e.startsWith("$")&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${e}" must not start with "$" (reserved namespace).${ae}`),e.includes("@")&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${ae}`),e in Object.prototype&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const t=oe(e);for(const n of t.segments)0===n.length&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${e}" has an empty path segment.${ae}`);return t.wildcardCount>d&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function Bg(e,t){const n=t[F];if(void 0===n)return null;"object"==typeof n&&null!==n||ee(`[wcs/watch-declaration-invalid] ${F} must be an object mapping state paths to handler functions.${ae}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&ee(`[wcs/watch-declaration-invalid] ${F} entry "${t}" must be a function.${ae}`);const n=Dg(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){Ag.set(e,t)}(e,o),s.size>0?s:null}const zg={writeObserve(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||Ng(n,o)},swapped(e,t,n){var o;o=n,kg.has(o)&&Ng(t,_g(n))}};function Fg(e){for(let t=e;null!==t;t=t.parentListIndex)if(qs(t))return!0;return!1}function qg(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[jt](bn(t.wildcardParentPathInfos[i],r)),l=Hs(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=nn(o,i,t.wildcardCount);if(l!==c&&!Bs(l,c)){if(qs(c))return"gone";s="replaced"}r=l}return s}function Vg(e,t,n){const o=new Map;for(const s of n){const n=qg(e,t,s);if("gone"===n)continue;const r="current"===n?1:0,i=s.indexes.join(","),a=o.get(i);(void 0===a||r>a.rank)&&o.set(i,{row:s,rank:r})}return Array.from(o.values(),e=>e.row)}const Hg=Object.freeze([]);function Kg(e,t,n){let o=e.get(n);return void 0===o&&(o={stateElement:t,entry:n,rows:[],reset:!1},e.set(n,o)),o}function Ug(e,t){let n=0;for(;n<e.indexes.length-1&&e.indexes[n]===t.indexes[n];)n++;return e.indexes[n]-t.indexes[n]}function Gg(e,t){return t.has(e.stateElement)&&!0===Yh(e.stateElement)?.entries.has(e.entry)}function Jg(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>Xg(n,e))||ip(t)}function Xg(e,t){return ar().hasQueuedPath(e,t)}function Qg(e,t){!function(e,t,n){if(0!==np)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=op(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||ip(t)}}(e,t,Xg)}function Yg(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function Zg(e,t,n){if(!Gg(e,n))return Jg(e),null;const{stateElement:o,entry:s}=e;if(e.reset)return{group:e,next:s.initial};const r=s.source;if(function(e,t){for(const n of t.pathInfo.cumulativePaths)if(e.getterPaths.has(n))return!0;return!1}(o,r))return function(e,t,n){if(Sp.has(e))return;Sp.add(e);const o=`[wcs/scan-source-computed] ${q} entry "${t}" from "${n}" is now backed by a getter (registered after the declaration, e.g. by a volume). A getter re-evaluates whenever its inputs change, so this scan stopped folding. Fold the plain value the getter reads instead.`;console.error(`[@wcstack/state] ${o}`),bp(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=Xp(e).get(t);if(void 0===o)return!1;for(const e of o.depAddresses)if(n.has(e))return!0;return!1}(o,r.pathInfo.segments[0],t))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",t=>{const n=t[s.name];i.failure="read-rows";const o=0===r.pathInfo.wildcardCount?e.rows:Vg(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(Ug)){let n;try{n=Yg(t,r,e)}catch(e){vp(s.name,e,"read-source");continue}const o=a(l,n,_g(e.absAddress),...e.indexes);if($p(o))return void xp(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){vp(s.name,e,i.failure)}return i.plan}function em(e,t){const{group:n}=e;if(!Gg(n,t))return void Jg(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||ip(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!hp(o,s.initial):!Object.is(o,e.next)){const o=n.reset?up(s.initial):e.next;t[s.name]=o,gp(s.name,o)}})}catch(e){vp(s.name,e,"write")}}function tm(e,t,n){if(Qg(e,t),0===Gh.size)return Hg;const o=new Map;for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=Yh(e);if(void 0===s)continue;const r=n.absolutePathInfo.pathInfo,i=s.byFromPath.get(r.path);if(void 0!==i){let t=[];if(r.wildcardCount>0){if(null===n.listIndex)continue;t=on(n.listIndex,r.wildcardCount)}for(const s of i)Kg(o,e,s).rows.push({absAddress:n,indexes:t})}const a=s.byResetPath.get(r.path);if(void 0!==a)for(const t of a)Kg(o,e,t).reset=!0}if(0===o.size)return Hg;const s=Array.from(o.values()).sort((e,t)=>e.entry.order-t.entry.order),r=[];$g(n);try{for(const n of s){const o=Zg(n,e,t);null!==o&&r.push(o)}}finally{xg()}return r}function nm(e){um(),(0!==Og(e).size||0!==Wg(e).size||function(e){const t=Uh.get(e);return void 0!==t&&Xh(t)}(e))&&(Tg(e),function(e){const t=[];for(const n of Og(e).values())om(e,n)&&t.push(n);for(const n of Wg(e).values())for(const o of n)om(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{Ig(e,Xt(e,o.pathInfo,null),n[o.path])}catch(t){rm(e,o.path,"prime",t)}})}(e))}function om(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const sm={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function rm(e,t,n,o){console.error(`[@wcstack/state] $watch ${sm[n]} "${t}" threw.`,o),null!==xt&&xt({type:"state:watch-error",phase:n,path:t,error:o})}function im(e){const t=Rg();try{if(0===t.size)return void Qg(e,t);const n=function(){const e=vg;return vg=0,e}();if(n>32){Qg(e,null);const t=Array.from(e,e=>e.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; $scan folds and $watch handlers for this batch were skipped.",{maxDepth:32,paths:t}),void(null!==xt&&xt({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}!function(e,t,n){if(0!==e.length){$g(n);try{for(const n of e)em(n,t)}finally{xg()}}}(tm(e,t,n),t,n),function(e,t,n){const o=[];for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=n.absolutePathInfo.pathInfo.path,r=Og(e).get(s),i=Wg(e).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const t of a){let s=[];if(t.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=on(n.listIndex,t.pathInfo.wildcardCount)}o.push({stateElement:e,entry:t,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(lm);const s=function(e){let t=null;for(let n=0;n<e.length;n++){const o=e[n];if(0===o.entry.pathInfo.wildcardCount)continue;const s=e[n-1];(Fg(o.absAddress.listIndex)||s?.entry===o.entry&&am(s.indexes,o.indexes))&&(t??=new Set).add(o.entry)}if(null===t)return e;const n=new Set;for(const o of t){const t=e.filter(e=>e.entry===o),s=t[0].stateElement;try{s.createState("readonly",e=>{const s=new Set(Vg(e,o.pathInfo,t));for(const e of t)s.has(e)||n.add(e)})}catch(e){rm(0,o.path,"evaluate",e);for(const e of t)n.add(e)}}return e.filter(e=>!n.has(e))}(o);$g(n);try{for(const e of s){if(!t.has(e.stateElement))continue;const n=Og(e.stateElement).get(e.entry.path)===e.entry,o=!0===Wg(e.stateElement).get(e.entry.path)?.includes(e.entry);(n||o)&&cm(e)}}finally{xg()}}(e,t,n)}finally{kg.clear()}}function am(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function lm(e,t){if(e.entry.order!==t.entry.order)return e.entry.order-t.entry.order;const n=Math.min(e.indexes.length,t.indexes.length);for(let o=0;o<n;o++)if(e.indexes[o]!==t.indexes[o])return e.indexes[o]-t.indexes[o];return e.indexes.length-t.indexes.length}function cm(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=om(t,n);try{t.createState("writable",e=>{let i;try{i=function(e,t,n){if(0===t.pathInfo.wildcardCount)return e[t.path];return e.$resolve(t.path,n)}(e,n,s)}catch(e){return void rm(0,n.path,"evaluate",e)}const a=r?function(e,t){return Pg.get(e)?.get(t)}(t,o):_g(o);r&&Ig(t,o,i),null!==xt&&xt({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){rm(0,n.path,"handler",e)}}let dm=!1;function um(){dm||(dm=!0,Cl("watch",zg),Tl("watch",fm),or(im,10),nr(Sg),ed={assertValidPath:Dg,addEntries:jg,start:nm})}const fm={order:10,register(e,t){var n;n=e,Eg.delete(n),ep(n),Ag.delete(n),function(e){Pg.delete(e)}(e);const o=Bg(e,t);e.setWatchPaths?.(o),null===o&&null==e.scanPaths||e.attachAddressHooks?.("watch",null!==o?F:q)},activate(e,n){t()||null==e.connectedRootNode||(null===n?!0===e.initialized:n===e.connectGeneration)&&nm(e)},deactivate(e){var t;t=e,Eg.delete(t),ep(t)}},hm=[qd,{name:"temporal",install(){um(),Dp||(Dp=!0,Tl("scan",Wp),nr(sp)),wg()}},mu,Ih,Kh,yd,_d];await function(e,t){!function(e){for(let t=0;t<e.length;t++)e[t].install()}(hm),Zc(e,t)}();
2
2
  //# sourceMappingURL=auto.min.js.map