wcstack 4.0.0-rc.3 → 4.0.0-rc.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/package.json +1 -1
package/dist/auto.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=class{constructor(e,n,r){this.h=[],this.getter=null,this.oe=null,this.de=!1,this.G=[],this.$e=[],this.ct=null,this.F=-1,this.J=t,this.Fe=null,this.Pt=null,this.Tt=null,this.q=null,this.At=new Set,this.t=e,this.d=r,this.s=n;let i=null===r?[null]:r.f.slice(),s="*"===n;s&&i.push(r),this.n=i.length-1,this.U=s?[]:null===r?[n]:[...r.U,n],this.f=i}jn(e){this.At.has(e)||(this.At.add(e),this.G.push(e),e.$e.push(this))}Po(){this.getter=null,this.oe=null,this.F=-1,this.J=t,this.G.length=0,this.At.clear(),this.$e.length=0,this.ct=null,this.Fe=null,this.Pt=null,this.Tt=null,this.q=null}Q(e){let t=this;for(;null!==t;){if(t===e)return!0;t=t.d}return!1}},t=Symbol("unset"),n=Symbol("dirty"),r=Symbol("failed"),i=class{constructor(e=null){this.Ft=new Map,this.Ln=e}Ot(e){return this.Ft.get(e)}get(t){let n=this.Ft.get(t);if(void 0!==n)return n;let r=t.lastIndexOf("."),i=r<0?null:this.get(t.slice(0,r));return n=new e(t,t.slice(r+1),i),this.Ln?.(n),this.Ft.set(t,n),i&&i.h.push(n),n}all(){return this.Ft.values()}},s=new Map;function o(e){let t=s.get(e);if(void 0!==t)return t;let n=!0,r=e.split("."),i=[];for(let e=0;e<r.length;e++){let t=r[e],s=t.charCodeAt(0);e>0&&s>=48&&s<=57?(n=!1,i.push(Number(t)),r[e]="*"):"*"===t&&i.push(-1)}if(!n)return{o:r.join("."),indexes:i};let o={o:e,indexes:null};return s.set(e,o),o}var l=class{constructor(e,t,n){this.ut=null,this.$=null,this.fe=null,this.q=null,this.h=null,this.y=!0,this.l=e,this.b=t,this.T=n}},a=class{constructor(e,t){this.C=null,this.u=[],this.$=null,this.L=null,this.Z=!1,this.Ct=!1,this.dt=!1,this.o=e,this.re=t,this.n=e.n+1}},u=[],c={};function h(e,t){return null==e?t:(...n)=>{e(...n),t(...n)}}function d(e,t,n){return null==t?n:(...r)=>{let i=t(...r);return e(i)?i:n(...r)}}var f=e=>!0===e,p=e=>void 0!==e,m=e=>null!=e,g=new Set;function y(e){let t=e.$features;if(null!=c.jt&&Array.isArray(t)){let e=t.filter(e=>!g.has(e));if(e.length>0)return c.jt(e)}}function b(e,t){if(!g.has(e))throw new Error(`[@wcstack/state] [wcs/feature-not-installed] ${t} needs the add-on @wcstack/state/features/${e}`)}function v(e,t,n){throw new Error(`[@wcstack/state] ${e}${c.Ao?.(e,t,n)??""}`)}var w=["","binding-syntax","template-syntax","binding-path-missing","binding-type-expectation","filter-unknown","filter-arity","getter-cycle","getter-depth-exceeded","index-arity","index-param-range","recursion-unsupported","token-misconfigured","token-undeclared","wildcard-rank","spread-no-bindable","declaration-alias","name-alias"],_=e=>{let t=w[e/100|0];return t?`[wcs/${t}] `:""};function $(e,t=[]){return c.Fo?.(e,t)??`${_(e)}#${e}${t.map(e=>` ${"string"==typeof e?JSON.stringify(e):String(e)}`).join("")}`}function k(e,t,n,r){v($(e,t),n,r)}var S=class{constructor(e){this.ft=new Set,this.name=e}get size(){return this.ft.size}subscribe(e){return this.ft.add(e),()=>{this.ft.delete(e)}}unsubscribe(e){return this.ft.delete(e)}emit(...e){let t=[];for(let n of this.ft)try{t.push(n(...e))}catch(e){t.push(void 0),console.error(`[@wcstack/state] ${$(17,[this.name])}`,e)}return t}};function N(e,t,n){if(void 0===e)return[];Array.isArray(e)||k(18,[t]);let r=new Set;for(let i of e)("string"!=typeof i||""===i)&&k(19,[t]),i===n&&k(20,[t,i,n]),r.has(i)&&k(21,[t,i]),r.add(i);return e}var A=Symbol.for("wcstack.transition-runner");function E(e){let t=globalThis[A];return null==t||"wcs-transition-runner"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.run||"function"!=typeof t.accepts||!t.accepts(e)?null:t}function C(e,t,n){let r=E(e);if(null!==r)return r.run(t,{source:e,types:n});t()}var x="else",T="eventToken",P=/^\$[1-9]\d{0,2}$/,O=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function M(e){let t=[],n=[],r="",i=null,s=!1,o=-1,l=-1,a=e=>{let i=function(e,t,n){let r=-1===t?e.length:t,i=-1===n?0:n;return e.slice(r-e.slice(0,r).trimStart().length,i+e.slice(i).trimEnd().length)}(r,o,l);(!e||i||s)&&(t.push(i),n.push(function(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:O.test(e)?Number(e):e)}(i,s))),r="",s=!1,o=-1,l=-1};for(let t=0;t<e.length;t++){let n=e[t];i?n===i?i=null:(-1===o&&(o=r.length),r+=n,l=r.length):'"'===n||"'"===n?(i=n,s=!0):","===n?a():r+=n}return null!==i&&k(107,[i,e]),a(!0),{args:t,literals:n}}var L=e=>e.trim();function I(e,t){let n=[],r=null;for(let i=0;i<e.length;i++){let s=e[i];null!==r?s===r&&(r=null):"'"===s||'"'===s?r=s:s===t&&n.push(i)}return n}var j=(e,t)=>I(e,t)[0]??-1;function R(e,t){let n=[],r=0;for(let i of I(e,t))n.push(e.slice(r,i)),r=i+1;return n.push(e.slice(r)),n}function H(e,t,n){let r=j(e,"|");if(-1===r)return[e.trim(),[]];let i=e.slice(r+1).trim(),s=n.get(i);return void 0===s&&(s=function(e,t,n){let r=n??e.join("|");return e.map(e=>{let n=j(e,"("),i=(e=>I(e,")").pop()??-1)(e);if(-1===i&&(i=e.lastIndexOf(")")),-1!==n&&-1===i&&k(108,[e]),-1!==i&&-1===n&&k(109,[e]),-1!==i&&i<n&&k(110,[e]),-1!==i&&e.slice(i+1).trim().length>0){let t=e.slice(i+1).trim();k(111,[e,t])}let s=(-1===n?e:e.substring(0,n)).trim();if(0===s.length&&k(112,[r]),s.includes("#")){let[,e]=s.split("#");k("input"===t?113:114,[s,e])}return-1===n?{Bn:s,args:[],literals:[]}:{Bn:s,...M(e.substring(n+1,i))}})}(R(i,"|").map(L),t,e),n.set(i,s)),[e.slice(0,r).trim(),s]}var W=new Map;function z(e){k(1101,[e])}function D(e){let[t,n]=H(e,"output",W);t.includes("@")&&k(32,[t]);let r=t,i=r.startsWith("."),s=i?r.slice(1):r;return(s.length>0&&s.split(".").some(e=>0===e.length)||!i&&0===s.length)&&k(119,[e]),function(e){e.includes("**")&&z(e);let t=e.split(".").length;t>512&&k(117,[e,t])}(r),{Je:r,Qe:n}}var U=[["$streams","$stream"],["$updatedCallback","$renderedCallback"]],F=[["$watch","temporal"],["$stream","temporal"],["$listKeys","list-keys"],["$recursion","recursion"]],q=["enableMustache","sameValueGuard","enableDirectionalInitialSync"];function B(e){return e.includes("**")&&z(e),e}var K=0;function G(e,t,n){let r=e.get(t);return void 0===r&&e.set(t,r=n()),r}var V=()=>new Set,J=()=>[];function Q(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}function X(e,t){return e===t||e!=e&&t!=t}function Y(e,t,n){let r=e.q?.get(t);void 0!==r&&r.delete(n)&&0===r.size&&e.q.delete(t)}function Z(e,t){for(let n=0;n<t.length;n++){if(null==e)return;e=e[t[n]]}return e}function ee(e,t){for(;null!==e&&e.l.n>t;)e=e.l.re;return null!==e&&e.l.n===t?e:null}function te(e,t,n){let r=ee(e,n);return null!==r&&r.l.o===t.f[n]?r:null}var ne=class{constructor(e,t){this.Oe=0,this.c=null,this.Ce=0,this.pt=new Set,this.Ze=new Map,this.Dn=Symbol("wcs.block"),this.element=null,this.mt=[],this.Ie=null,this.Mn=[],this.Mt=0,this.K=null,this.ee=new Map,this.ie=new Map,this.je=[],this.Le=[],this.Be=[],this.ht=!1,this.dn=!1,this.Wt=new WeakMap,this.M=0,this._t=0,this.fn=!1,this.Ht=!1,this.Vt=!1,this.xe=0,this.Wn=()=>{this.M=0,this.fn=!1},this._n=()=>{this.xe--},this.rp=null,this.rr=null,this.Oo=()=>this.Ut(),this.Co=(e,t)=>e(this.proxy,...t),this.Hn=[],this.Io={$untracked:e=>{let t=this.K;if(null===t)return e();t.pe++;try{return e()}finally{t.pe--}},$eqIndex:(e,t=1)=>{let n=ee(this.c,t);null===n&&k(7,[e]);let r=this.o(e);if(null!==r.getter||r.de)return this.watchIndex(t),n.b===this.read(r,null);let i=this.K;if(null!==i){let e=i.getter,n=r.Fe??(r.Fe=[]);if(!n.some(n=>n.getter===e&&n.Vn===t)){n.push({getter:e,Vn:t});let i=e.f[t];(i.Pt??(i.Pt=[])).push({source:r,getter:e})}}return n.b===this.v(r,null)},$eq:(e,t)=>this.eq(e,t),$eqPath:(e,t)=>{let n=this.o(t);return this.eq(e,this.v(n,ee(this.c,n.n)))},$dependOn:e=>{this.resolve(B(e),this.c),null!==this.K&&0===this.K.pe&&this.Un(this.rp,this.rr,this.K)},$getAll:(e,t)=>this.getAll(e,t),$setAll:(e,t,n,r)=>this.pn(e,t,n,r),$resolve:(...e)=>{let t=B(e[0]),n=e[1]??[],r=this.o(t);this.mn("$resolve",t,r,n,!0);let i=this.qn(r,n,null);if(e.length<3)return this.read(r,i);this.P(r,i,e[2])},$postUpdate:e=>{this.resolve(B(e),this.c);let t=this.rp,n=this.rr;"*"===t.s&&null!==n&&(n.T=n.l.C[n.b],this.R.qt(n)),this.hn(t,n),null!==n&&this.Kn(n,t,void 0,n.T,!1),0===t.n&&this.zn(t,void 0,void 0,!0),this.Kt(t,n,void 0,void 0,!1)}},this.R=t,this.B=new i(e=>this.et(e)),this.Xn(e);let n=this,r={getOwnPropertyDescriptor(e,t){let r=Reflect.getOwnPropertyDescriptor(n.target,t);return r&&(r.configurable=!0),r},get(e,t,r){let i=n.target;if("symbol"==typeof t)return Reflect.get(i,t);if(36===t.charCodeAt(0))return n.zt(t);if(t.indexOf(".")<0){let e=n.B.Ot(t);if(void 0===e||null===e.getter){let e=i[t];if("function"==typeof e)return r===n.proxy&&n.W?.(e)||e}if(void 0!==e&&0===e.n)return n.read(e,null)}return n.resolve(t,n.c),n.read(n.rp,n.rr)},set:(e,t,r)=>"symbol"==typeof t?Reflect.set(n.target,t,r):(n.resolve(B(t),n.c),n.P(n.rp,n.rr,r),!0)};for(let e of["has","ownKeys","deleteProperty","defineProperty","getPrototypeOf"])r[e]=(t,...r)=>Reflect[e](n.target,...r);this.proxy=new Proxy({},r)}o(e){return this.B.get(e)}Yn(e){let t=new Set;for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n))for(let e of Object.getOwnPropertyNames(n)){if(t.has(e))continue;t.add(e);let r=Object.getOwnPropertyDescriptor(n,e);if(void 0===r.get&&void 0===r.set)continue;let i=this.o(e);i.getter=r.get??null,i.oe=r.set??null,null!==i.getter&&i.n>0&&(i.F=this.Oe++)}for(let e of this.B.all())this.et(e)}et(e){e.t.includes("**")&&z(e.t),("__proto__"===e.s||"prototype"===e.s)&&k(120,[e.t]);let t=e.d;e.de=null!==t&&"*"!==e.s&&t.n===e.n&&(null!==t.getter||t.de),null===e.getter&&this.jo(e)}jo(e){let t=e.t,n=e.s;if(P.test(n))e.getter=function(){return this[n]};else{let r=t.split("."),i=r.findIndex((e,t)=>t>0&&e.charCodeAt(0)>=48&&e.charCodeAt(0)<=57);if(i<0||r.indexOf("*",i)>=0)return;e.getter=()=>(this.resolve(t,this.c),this.rp!==e?this.read(this.rp,this.rr):this.read(e.d,this.c)?.[n]),e.oe=r=>{if(this.resolve(t,this.c),this.rp!==e)return this.P(this.rp,this.rr,r);let i=this.read(e.d,this.c);null==i&&k(4,[t,i]),i[n]=r}}e.n>0&&(e.F=this.Oe++)}De(e,t){let n=null===e?this.ee:e.h??=new Map,r=n.get(t);return void 0===r&&n.set(t,r=new a(t,e)),this.z(r),r}Gn(e){try{this.z(e)}catch(t){this.Xt(t,e.o.t,e.$?.S??null,"for")}}z(e){let t=this.v(e.o,e.re);if(t===e.C)return;this.Jn(e);let n=function(e,t,n){let r=Array.isArray(t)?t:u;if(r===e.C)return null;let i=e.u,s=r.length,o=i.length,a=new Array(s),c=0;for(;c<s&&c<o&&i[c].T===r[c];)a[c]=i[c],c++;let h=o-1,d=s-1;for(;h>=c&&d>=c&&i[h].T===r[d];)a[d]=i[h],h--,d--;if(c>h)for(let t=c;t<=d;t++)a[t]=new l(e,t,r[t]);else if(c>d)for(let e=c;e<=h;e++)n.It(i[e]);else{let t=new Map;for(let e=c;e<=h;e++){let n=i[e],r=t.get(n.T);void 0===r?t.set(n.T,n):Array.isArray(r)?r.push(n):t.set(n.T,[r,n])}for(let n=c;n<=d;n++){let i,s=r[n],o=t.get(s);void 0!==o&&(Array.isArray(o)?(i=o.shift(),0===o.length&&t.delete(s)):(i=o,t.delete(s))),a[n]=i??new l(e,n,s)}for(let e of t.values())if(Array.isArray(e))for(let t of e)n.It(t);else n.It(e)}for(let e=c;e<s;e++){let t=a[e];t.b!==e&&(t.b=e,n.To(t))}return e.u=a,e.C=r,i}(e,t,this);if(null===n)return;if(e.C===t){let n=G(this.Wt,t,J);if(n.push(e),n.length>1)for(let e of n)e.dt=!0}c.Yt?.(this,e,n),(null!==e.$||null!==e.L)&&!e.Z&&(e.Z=!0,this.Le.push(e),this.Re());let r=e.o.Pt;if(null!==r)for(let{source:t,getter:i}of r){let r=this.v(t,null),s=n[r],o=e.u[r];s!==o&&(void 0!==s&&s.y&&this.gn(i,s),void 0!==o&&this.gn(i,o))}}To(e){this.R.Lo(this,e)}It(e){e.y=!1;let t=e.q;if(null!==t){for(let e of t)Y(e.source,e.key,e.sub);e.q=null}if(null!==e.h)for(let t of e.h.values()){this.Jn(t);for(let e of t.u)this.It(e)}}Jn(e){let t=this.Wt.get(e.C);void 0!==t&&(t.splice(t.indexOf(e)>>>0,1),e.dt=!1,1===t.length&&(t[0].dt=!1))}resolve(e,t){let n=o(e),r=this.rp=this.o(n.o),i=n.indexes;this.rr=0===r.n?null:null===i?te(t,r,r.n):this.qn(r,i,t,e)}qn(e,t,n,r){let i=null;for(let s,o=1,l=0;o<=e.n;o++){let a=e.f[o],c=this.De(i,a),h=t[l++];if(h<0)h=te(n,e,o)?.b??-1;else if(r&&c.C===u&&Object(s=this.v(a,i))===s){let t=e.t.split("."),n=a.t.split(".").length;t[n]=r.split(".")[n],e=this.o(t.join(".")),o--;continue}if(i=c.u[h]??null,null===i)break}return this.rp=e,i}yt(e,t){return 0===e.n?Z(this.target,e.U):null===t?void 0:Z(t.T,e.U)}read(e,t){let n=this.K;if(null!==n&&0===n.pe&&this.Un(e,t,n),null!==e.getter)return this.R.Bo(this,e,t);if(e.de){let n=this.read(e.d,t);return n?.[e.s]}return null===e.d&&!(e.s in this.target)&&!this.pt.has(e.s)&&"then"!==e.s&&"toJSON"!==e.s&&k(301,[e.t],e.s,Object.keys(this.target)),this.yt(e,t)}v(e,t){let n=this.K;if(null===n)return this.read(e,t);n.pe++;try{return this.read(e,t)}finally{n.pe--}}Un(e,t,n){let r=n.getter;e.jn(r),e.n>0&&r.n>0&&ee(t,Math.min(e.n,r.n))!==ee(n.r,Math.min(e.n,r.n))&&(r.ct??(r.ct=new Set)).add(e)}Do(e,t){for(let n=0;n<this.Mt;n++){let r=this.Mn[n];r.getter===e&&r.r===t&&k(701,[e.t])}this.Mt>=128&&k(801,[e.t]);let n=this.Mt++;this.Ce++;let r=this.Mn[n]??={getter:e,r:t,pe:0,Me:0};r.getter=e,r.r=t,r.pe=0,r.Me=++K;let i=this.K;this.K=r;let s=this.c;this.c=t;try{return e.getter.call(this.proxy)}finally{this.Ce--,this.Mt--,this.K=i,this.c=s,r.r=null}}watchIndex(e){let t=this.K;if(null!==t&&0===t.pe){let n=t.getter,r=n.f[e];if(r){let e=r.Tt??(r.Tt=[]);e.includes(n)||e.push(n)}}}zt(e){let t=e.charCodeAt(1);if(t>=48&&t<=57){let n=2===e.length?t-48:P.test(e)?+e.slice(1):0;return(n<1||n>128)&&k(1001,[e]),this.watchIndex(n),ee(this.c,n)?.b}let n=this.Io[e];if(void 0!==n)return n;switch(e){case"$trackDependency":return k(1701,[e,"$dependOn"]);case"$untrackDependency":return k(1701,[e,"$untracked"]);case"$stateElement":return this.element;case"$command":return this.commands}return c.zt?.(this,e)}eq(e,t){this.resolve(e,this.c);let n=this.rp,r=this.rr;if(null!==n.getter||n.de||n.n>0)return X(this.read(n,r),t);let i=this.K;return null!==i&&0===i.pe&&this.Mo(n,t,i),X(this.v(n,null),t)}Mo(e,t,n){let r=n.getter,i=n.r,s=null===i?this.Hn:i.q??(i.q=[]);for(let i=0;i<s.length;i++){let o=s[i];if(o.sub.getter===r&&o.source===e){if(X(o.key,t))return void(o.Me=n.Me);o.Me!==n.Me&&(Y(e,o.key,o.sub),s.splice(i--,1))}}let o={getter:r,r:i};G(e.q??=new Map,t,V).add(o),s.push({source:e,key:t,sub:o,Me:n.Me})}zn(e,t,n,r){this.Gt(e,i=>{let s=i.q;if(null===s&&null===i.Fe)return;let o=i===e?[]:i.t.slice(e.t.length+1).split("."),l=Z(t,o),a=Z(n,o);if(null!==i.Fe&&this.Wo(i,l,a,r),null!==s)for(let e of r?s.keys():[l,a]){let t=s.get(e);if(void 0!==t)for(let n of t)null===n.r||n.r.y?this.R.me(this,n.getter,n.r):Y(i,e,n)}})}P(e,t,n,r=!1,i=!1){if(this.Ce>0&&k(8),i||this.xe>0?this.Ht=!0:this.Vt=!0,c.Pe?.(this,e,t,n,i))return;if(null!==e.oe){try{this.yn(e.oe,t,[n])}finally{this.Kt(e,t,void 0,void 0,!1)}return}null!==e.getter&&k(2,[e.t]),e.n>0&&null===t&&k(3,[e.t]);let s=e.de?this.v(e,t):this.yt(e,t);if(r||!this.Bt||!Object.is(s,n)||Object(n)===n){if("*"===e.s){let e=t;e.l.C[e.b]=n,e.T=n,this.R.qt(e)}else{let r=1===e.U.length?0===e.n?this.target:t.T:this.v(e.d,t);null==r&&k(4,[e.t,r]),r[e.s]=n}this.wn(e,t),null!==t&&this.Kn(t,e,s,n),0===e.n&&this.zn(e,s,n),this.Kt(e,t,s,n,!0)}}Qn(e){return(this.Wt.get(e.C)??[]).filter(t=>t.C===e.C&&(null===t.re||t.re.y))}Kn(e,t,r,i,s=!0){let o=e.l;if(!o.dt&&null===o.o.getter&&!o.o.G.length)return;let l=e.T,a=t.t.slice(o.o.t.length+2),u=(t,n)=>{if(void 0===n||n===e)return;let o=this.o(`${t.o.t}.*${a}`);""===a&&(n.T=i,this.R.qt(n)),s?this.wn(o,n):this.hn(o,n),this.Kt(o,n,r,i,s)};for(let t of this.Qn(o))u(t,t.u[e.b]);if(""===a)return;let c=new Set([o.C]),h=e=>Array.isArray(e)&&e.includes(l),d=(e,t)=>{if(!c.has(e)&&c.add(e))for(let t of this.Wt.get(e)??[])for(let e of t.u)e.T===l&&u(t,e);for(let r of t){let t=r.J,i=t===n;i&&(t=this.ee.get(r)?.C),(i||h(t))&&!c.has(r.G)&&c.add(r.G)&&(!i&&t!==e&&this.R.me(this,r,null),d(t,r.G))}},f=e=>{for(let t of e.$e)if(!c.has(t)&&c.add(t))if(null!==t.getter)f(t);else if(!t.de){let e=this.yt(t,null);h(e)&&d(e,t.G)}};null!==o.o.getter?f(o.o):d(o.C,o.o.G)}hn(e,t){this._o(e,t,e=>{this.z(e);for(let t of e.dt?this.Qn(e):[e]){let e=this.o(`${t.o.t}.*`);for(let n of t.u)this.wt(e,n),this.hn(e,n)}})}wn(e,t){let n=null===t?this.ee:t.h;if(null!==n)for(let t of n.values())t.o.Q(e)&&this.z(t)}_o(e,t,n){let r=null===t?this.ee:t.h;if(null!==r)for(let t of r.values())t.o.Q(e)&&n(t)}Wo(e,t,n,r){for(let{getter:i,Vn:s}of e.Fe)this.Zn(i.f[s],e=>{for(let s of r?e.u.keys():[t,n]){let t="number"==typeof s?e.u[s]:void 0;void 0!==t&&this.gn(i,t)}})}gn(e,t){t.l.n===e.n?this.R.me(this,e,t):this.Jt(t,e,t=>this.R.me(this,e,t))}Kt(e,t,n,r,i){c.he?.(this,e,t,n,r,i),this.We(e,t)}We(e,t){this.R.Ho(this,e,t),this.Re()}eo(e){let t=this.Ze.get(e);if(void 0!==t)return t;let n=Symbol(`wcs.on${e}`);this.Ze.set(e,n);let r=this.root,i=this.Dn;return r.addEventListener(e,t=>{for(let s=t.target;null!==s&&s!==r;s=s.parentNode){let r=s[n];if(void 0!==r&&(r(t),t.cancelBubble))return;let o=s[i];if(void 0!==o&&o.y&&o.Vo(e,t))return}}),n}reset(e){let t=this.target,n=this.pt;for(let e of this.B.all())null===e.d&&null!==e.getter&&n.add(e.s);this.Xn(e);for(let e in t)"$"!==e[0]&&n.add(e);for(let t of n)t in e&&n.delete(t);for(let e of this.ie.values())for(let t of e)this.Qt(t);for(let e of this.ee.values())this.to(e);this.Ie=null;try{this.Ut()}finally{this.bn()}c.element?.(this,"reset")}Xn(e){for(let[t,n]of F)void 0!==e[t]&&b(n,t);void 0!==e.$scan&&k(1);for(let[t,n]of U)void 0!==e[t]&&k(1601,[t,n]);let t=e.$features;if(void 0!==t){Array.isArray(t)||k(46);for(let e of t)b(e,"$features")}let n=void 0===e.$behavior?{}:e.$behavior;("object"!=typeof n||!n||Array.isArray(n))&&k(44,["state","$behavior"]);for(let e in n)(!q.includes(e)||"boolean"!=typeof n[e])&&k(44,["$behavior",e]);let[r,i,s]=q.map(e=>n[e]??!0);void 0!==this.target&&(r!==this.Lt||i!==this.Bt||s!==this.Dt)&&k(45);let o=function(e,t){let n={};for(let r of N(e.$commandTokens,"$commandTokens","$command"))n[r]=t?.[r]??new S(r);return Object.freeze(n)}(e,this.commands),l=function(e,t){let n=new Map;for(let t of N(e.$eventTokens,"$eventTokens"))n.set(t,new S(t));let r=e.$on;if(void 0===r)return n;(null===r||"object"!=typeof r)&&k(22);for(let[e,i]of Object.entries(r)){let r=n.get(e);void 0===r&&k(23,[e]),"function"!=typeof i&&k(24,[e]),r.subscribe((...e)=>t(i,e))}return n}(e,this.Co);this.Lt=r,this.Bt=i,this.Dt=s,c.se?.(this,e),this.target=e,this.Oe=0;for(let e of this.B.all())e.Po();this.Hn.length=0,this.Yn(e),this.commands=o,this.Ne=l}to(e){this.Gn(e);let t=this.o(`${e.o.t}.*`);for(let n of e.u)if(n.ut=null,n.q=null,this.wt(t,n),null!==n.h)for(let e of n.h.values())this.to(e)}_(e){let t=[];for(let n=e;null!==n;n=n.l.re)t.unshift(n.b);return t}Uo(e,t,n){let r=this.Ne.get(e);void 0===r&&k(1301,[e],e,this.Ne.keys()),r.emit(t,...this._(n))}command(e){let t=this.commands[e];return void 0===t&&k(1302,[e],e,Object.keys(this.commands)),t}qo(e,t,n){this.command(e).emit(t,...this._(n))}Ko(e,t,n){let r=e.includes(".")?this.v(this.o(e),null):this.target[e];return"function"!=typeof r&&k(5,[e]),this.yn(r,n,[t,...this._(n)])}yn(e,t,n){let r=this.c;this.c=t;try{return e.apply(this.proxy,n)}finally{this.c=r}}wt(e,t){if(null!==e.getter){let n=null===t?this.ee:t.h;if(null!==n)for(let t of n.values())!t.Ct&&t.o.Q(e)&&(t.Ct=!0,this.Be.push(t))}if(null===t)return void this.Gt(e,e=>{let t=this.ie.get(e);if(void 0!==t)for(let e of t)this.Qt(e)});let n=t.fe;if(null!==n)for(let t=0;t<n.length;t++)n[t].o.Q(e)&&this.Qt(n[t]);let r=t.$;null!==r&&null!==r.ae&&r.no(this,e);let i=t.l.L;if(null!==i)for(let n of i){let r=n.map.get(t);void 0!==r&&null!==r.ae&&r.no(this,e)}}vn(e,t,n){this.Gt(e,e=>{let r=e.G;for(let i=0;i<r.length;i++){let s=r[i];if(0===s.n)this.tt(s,null,n);else if(null===t||0===e.n||s.f[1]!==e.f[1]||null!==s.ct&&s.ct.has(e))this.Zt(s.f[s.n],e=>this.tt(s,e,n));else if(s.n<=e.n){let e=ee(t,s.n);null!==e&&this.tt(s,e,n)}else this.Jt(t,s,e=>this.tt(s,e,n))}})}tt(e,t,n){n(e,t)&&(c.ye?.(this,e,t),this.wt(e,t),this.vn(e,t,n))}Gt(e,t){t(e);let n=e.h;for(let e=0;e<n.length;e++)this.Gt(n[e],t)}Zt(e,t){this.Zn(e,e=>{for(let n of e.u)t(n)})}Zn(e,t){if(0===e.n){let n=this.ee.get(e);return void(void 0!==n&&t(n))}this.Zt(e.f[e.n],n=>{let r=n.h?.get(e);void 0!==r&&t(r)})}Jt(e,t,n){if(e.l.n===t.n)return n(e);let r=e.h?.get(t.f[e.l.n+1]);if(void 0!==r)for(let e of r.u)this.Jt(e,t,n)}zo(e){let t=e.r;null===t?G(this.ie,e.o,V).add(e):(t.fe??(t.fe=[])).push(e)}kn(e){let t=e.r;if(null===t)return void this.ie.get(e.o)?.delete(e);let n=t.fe;t.y&&null!==n&&n.splice(n.indexOf(e)>>>0,1)}Qt(e){e.Z||(e.Z=!0,this.je.push(e),this.Re())}Re(){this.ht||(this.ht=!0,queueMicrotask(this.Oo))}Sn(){for(let e of this.je)e.Z=!1;for(let e of this.Le)e.Z=!1;for(let e of this.Be)e.Ct=!1;this.je=[],this.Le=[],this.Be=[],this.R.pt(this)}oo(e,t){let n=[...new Set([...this.je,...this.Le,...this.Be].map(e=>e.o.t))];console.error(`[@wcstack/state] ${$(e)}`,n),c.nt?.(this,{type:"state:render-chain-limit",maxDepth:t,paths:n}),this.Sn()}Ut(){this.ht=!1;let e=this._t;this._t=0;let t=0;if(!this.Ht||this.Vt?this.Wn():e>0?t=e:1===(t=++this.M)&&setTimeout(this.Wn,0),this.Ht=this.Vt=!1,t>100)101===t?this.oo(41,100):this.Sn();else{this.dn=!0;try{for(let e=0;this.je.length>0||this.Le.length>0||this.Be.length>0;e++){if(e>=32){this.fn?this.Sn():this.oo(11,32),this.fn=!0;break}let n=this.Be;if(n.length>0){this.Be=[];for(let e of n)e.Ct=!1,this.Gn(e)}let r=this.Le,i=this.je;this.Le=[],this.je=[];let s=C("state",()=>{for(let e of r){e.Z=!1;for(let t of[e.$,...e.L??[]])if(null!==t&&t.y)try{t.bt()}catch(n){this.Xt(n,e.o.t,t.S,"for")}}for(let e=0;e<i.length;e++){let t=i[e];t.Z&&(t.Z=!1,(null===t.En||t.En.y)&&this._e(t))}this.dn||(this.He(),this.ht&&(this._t=t+1))});void 0!==s&&s.then(void 0,e=>console.error(e))}}finally{this.dn=!1}this.Ht=this.Vt=!1,this.He(),c.Te?.(this),e>0&&this.ht&&(this._t=t+1)}}vt(e,t){this.mt.push([e,t])}Xt(e,t,n,r){this.vt(e,{o:{t:t},a:n,en:()=>r})}_e(e){try{e.apply()}catch(t){return void this.mt.push([t,e])}null!==this.Ie&&this.io(e.o,e.r)}io(e,t){let n=G(this.Ie,e.t,J);null!==t&&n.push(this._(t))}bn(){this.Ie="function"==typeof this.target.$renderedCallback?new Map:null}He(){let e=this.Ie;if(null!==e&&e.size>0){this.Ie=new Map;let t,n=[...e.keys()],r={};for(let[t,n]of e)n.length>0&&(r[t]=n);this.xe++;try{t=this.we("$renderedCallback",[n,r])}catch(e){console.error(e)}Q(t)?t.then(this._n,e=>{this._n(),console.error(e)}):this.xe--}if(0===this.mt.length)return;let t=this.mt;this.mt=[];let n=this.target.$errorCallback;for(let[r,i]of t){c.Ve?.(this,r,i);let t=i.o.t,s=i.en();if("function"==typeof n)try{let e=this.we("$errorCallback",[r,{path:t,bindingType:s,node:i.a}]);Q(e)&&e.then(void 0,e=>console.error(e))}catch(e){console.error(e)}else console.error(`[@wcstack/state] ${$(12,[s,t])}`,r)}}we(e,t=[]){let n=this.target[e];return"function"==typeof n?this.yn(n,null,t):void 0}so(e,t,n){if(0===e.n)return void n(null,[]);let r=[],i=(s,o)=>{let l=e.f[s];this.read(l,o);let a=this.De(o,l),u=t=>{r.push(t.b),s===e.n?n(t,r):i(s+1,t),r.pop()};for(let e of s-1<t.length?[a.u[t[s-1]]]:a.u)void 0!==e&&u(e)};i(1,null)}getAll(e,t){let n=this.o(e);void 0!==t&&this.mn("$getAll",e,n,t,!1);let r=t;if(void 0===r){r=[];let t=this.c;if(null!==t&&n.n>0){for(let e=1;e<=n.n;e++){let i=te(t,n,e);if(null===i)break;r.push(i.b)}0===r.length&&k(6,[e])}}let i=[];return this.so(n,r,e=>i.push(this.read(n,e))),i}pn(e,t,n,r){Array.isArray(t)||k(9,[e]),this.Ce>0&&k(8);let i=this.o(e);this.mn("$setAll",e,i,t,!1);let s=[];this.so(i,t,(e,t)=>s.push([e,t.slice()]));let o=!0===r?.spread;o&&(!Array.isArray(n)||n.length!==s.length)&&k(10,[e,s.length]);let l=0;for(let e=0;e<s.length;e++){let[t,r]=s[e],a="function"==typeof n?n(this.v(i,t),...r):o?n[e]:n;void 0!==a&&(this.P(i,t,a),l++)}return l}mn(e,t,n,r,i){let s=r.length;(s>n.n||i&&s<n.n)&&k(i?901:902,[e,t,n.n,s])}},re={bindAttributeName:"data-wcs",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:typeof document<"u"&&document.documentElement?.lang||"en"},ie=new Map,se=new Set(["if","elseif","else","for"]),oe=new Set([x,"if","elseif","for","..."]),le=new Set(["class","attr","style","command",T,"state"]);function ae(e){let t=function(e){return R(e,";")}(e).map(L).filter(e=>e.length>0).map(e=>{let t=j(e,":");-1===t&&k(101,[e]);let n=e.slice(0,t).trim(),r=e.slice(t+1).trim(),i=n.split("#")[0].split("|")[0].trim();if(oe.has(i)){let t;return i!==n&&k(102,[e,i]),i===x?(r.length>0&&k(103,[e]),t={Je:"#else",Qe:[]}):"..."===i?(0===r.length&&k(104,[e]),t=D(r),t.Qe.length>0&&k(105,[e])):(t=D(r),"for"===i&&t.Qe.length>0&&k(121,[e])),{be:i,ve:[i],tn:[],I:[],...t,w:"..."===i?"spread":i}}let s=D(r),o=function(e){let[t,n]=H(e,"input",ie),r=t.split("#").map(L);r.length>2&&k(115,[t]);let[i,s]=r,o=i.split(".").map(L);return!(o.length>1&&""===o[0])&&(0===i.length||o.some(e=>0===e.length))&&k(116,[e]),{be:i,ve:o,tn:s?s.split(",").map(L):[],I:n}}(n),[l]=o.ve;if(""===l&&o.ve.length>1){let e=o.ve.slice(1);return(e.includes("")||le.has(e[0]))&&k(106,[n]),{...o,be:e.join("."),ve:e,...s,w:"prop"}}return{...o,...s,w:"radio"===i||"checkbox"===i?i:l===T||l.startsWith("on")?"event":"prop"}});return t.length>1&&t.some(e=>se.has(e.w))&&k(201,[e]),t}var ue=["toFixed","locale","upper","lower","capitalize","trim","slice","padStart","padEnd","repeat","reverse","truncate","join","round","floor","ceil","percent","unit","date","time","datetime","ymd","hms"],ce=new Map,he=new Map;function de(e){for(let t of Object.keys(e))ce.set(t,{...e[t]});he.clear()}function fe(e){return ce.has(e)}function pe(e){k(26,[e])}function me(e){k(27,[e])}function ge(e){k(28,[e])}function ye(e){k(29,[e])}function be(e){return!(!e||isNaN(Number(e)))}function ve(e,t){return be(e)||me(t),Number(e)}function we(e,t,n){return ve(e?.[t]??pe(n),n)}function _e(e,t){return void 0!==t&&t.length>0?t[0]:e}var $e=(e,t)=>({factory:n=>{let r=we(n,0,e);return n=>("number"!=typeof n&&ge(e),t(n,r))},arity:[1,1]}),ke={eq:{factory:(e,t)=>{let n=e?.[0]??pe("eq"),r=_e(n,t);return e=>"number"==typeof e?"string"!=typeof r?e===r:(be(n)||me("eq"),e===Number(n)):"string"==typeof e?e===n:e===r},arity:[1,1]},ne:{factory:(e,t)=>{let n=e?.[0]??pe("ne"),r=_e(n,t);return e=>"number"==typeof e?"string"!=typeof r?e!==r:(be(n)||me("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==r},arity:[1,1]},not:{factory:()=>e=>!e,arity:[0,0]},lt:$e("lt",(e,t)=>e<t),le:$e("le",(e,t)=>e<=t),gt:$e("gt",(e,t)=>e>t),ge:$e("ge",(e,t)=>e>=t),add:$e("add",(e,t)=>e+t),sub:$e("sub",(e,t)=>e-t),mul:$e("mul",(e,t)=>e*t),div:$e("div",(e,t)=>e/t),mod:$e("mod",(e,t)=>e%t),abs:{factory:()=>e=>("number"!=typeof e&&ge("abs"),Math.abs(e)),arity:[0,0]},clamp:{factory:e=>{let t=we(e,0,"clamp"),n=we(e,1,"clamp");return e=>("number"!=typeof e&&ge("clamp"),Math.min(Math.max(e,t),n))},arity:[2,2]},int:{factory:()=>e=>parseInt(String(e),10),arity:[0,0]},float:{factory:()=>e=>parseFloat(String(e)),arity:[0,0]},falsy:{factory:()=>e=>!e,arity:[0,0]},truthy:{factory:()=>e=>!!e,arity:[0,0]},defaults:{factory:(e,t)=>{let n=_e(e?.[0]??pe("defaults"),t);return e=>e||n},arity:[1,1]},coalesce:{factory:(e,t)=>{let n=_e(e?.[0]??pe("coalesce"),t);return e=>e??n},arity:[1,1]},boolean:{factory:()=>e=>!!e,arity:[0,0]},number:{factory:()=>e=>Number(e),arity:[0,0]},string:{factory:()=>e=>String(e),arity:[0,0]},nullIfEmpty:{factory:()=>e=>""===e?null:e,arity:[0,0]}},Se=!1;function Ne(e,t){if(null!==e)for(let n=0;n<e.length;n++)t=e[n](t);return t}function Ae(e){return 0===e.length?null:(Se||(Se=!0,de(ke)),e.map(e=>function(e,t,n){let r=`${e}${function(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}(t,n)}`,i=he.get(r);if(typeof i<"u")return i;let s=ce.get(e);void 0===s&&function(e,t){ue.includes(e)&&v(`[wcs/filter-unknown] filter not found: ${e}. "${e}" is in the formats add-on — install it with installFeatures([formats]) from "@wcstack/state/features/formats".`,e,t),k(501,[e],e,t)}(e,ce.keys());let[o,l]=s.arity;t.length<o&&k(601,[e,o,t.length]),t.length>l&&k(602,[e,l,t.length]);let a=s.factory(t,n);return he.set(r,a),a}(e.Bn,e.args,e.literals)))}var Ee=Symbol.for("wcstack.trustedTypes.policy");function Ce(){let e=globalThis[Ee];return null!==e&&"object"==typeof e?e:null}function xe(e){return"innerHTML"===e||"outerHTML"===e||"srcdoc"===e}function Te(e){if(globalThis.trustedTypes?.isHTML(e))return e;let t=null==e?"":String(e),n=Ce(),r=n?.createHTML;return"function"==typeof r?r.call(n,t):t}var Pe=Symbol.for("wcstack.state.view-transition-naming"),Oe=new WeakSet;function Me(){let e=E("state");return null!==e&&"auto"===e.naming?e.namingLimit:-1}var Le=new WeakMap,Ie=e=>e.customElementRegistry??customElements;function je(e,t,n,r,i,s=!1){let o=n.localName;if(!o.includes("-"))return i(null);let l=Ie(n);if(!s&&!n.isConnected&&void 0===l.get(o)&&"customElementRegistry"in n)return void queueMicrotask(()=>je(e,t,n,r,i,!0));let a=()=>{let e=l.get(o);l.upgrade(n),i(e?function(e){if(Le.has(e))return Le.get(e);let t=e.wcBindable,n=null;if(null!==t&&"object"==typeof t&&"wc-bindable"===t.protocol&&Number.isInteger(t.version)&&t.version>=1){n={properties:new Map,inputs:new Map,commands:new Set};for(let e of t.properties??[])n.properties.set(e.name,{event:e.event,getter:"function"==typeof e.getter?e.getter:null,lo:"event"===e.semantics});for(let e of t.inputs??[])n.inputs.set(e.name,{attribute:"string"==typeof e.attribute?e.attribute:null});for(let e of t.commands??[])null!==e&&"object"==typeof e&&"string"==typeof e.name&&n.commands.add(e.name)}return Le.set(e,n),n}(e):null)};if(!s&&void 0!==l.get(o))return a();null!==r&&!r.y||function(e,t,n){let r=n;null!==t&&(t.kt??=[]).push(()=>{r=null}),e.then(()=>r?.())}(l.whenDefined(o),r,()=>{try{a()}catch(r){Ue(e,r,t,n)}e.Re()})}function Re(e,t,n,r,i=t.o,s,o,l){let a=l.properties.get(r)??null,u=l.inputs.get(r),h=e.Dt;h&&null===a&&void 0===u&&k(38,[r]);let d=t.H;(null===a?"element"===d||"auto"===d:void 0===u&&("state"===d||"auto"===d))&&k(39,[d,r]),"connect"===t.z&&null===a&&k(40,[r]);let f=h&&null!==a&&void 0===u,p=new Be(e,ze,n,r,i,s,o,t.N,void 0);p.I=t.I,p.attribute=u?.attribute??null,Ze(e,p,!f),null!==a&&!t.ro&&n.addEventListener(a.event,t=>{let i;null!==a.getter?i=a.getter(t):(i=t.detail,a.lo||c.detail?.(n,r,i)),(!p.$n||!Object.is(i,p.value))&&(i=Ne(p.I,i),null===p.N&&(p.value=i),e.P(p.o,p.r,i,a.lo,!0))});let m=d??(f?"element":"state");if("state"===m)f||e._e(p);else if("element"===m||"auto"===m){let i=()=>{if(null!==o&&!o.y)return;if("auto"===m&&void 0!==e.v(p.o,p.r))return void(f||e._e(p));let t=n[r];null===p.N&&(p.value=t),e.P(p.o,p.r,t,!1,!0)};"connect"!==t.z||n.isConnected?i():Promise.resolve().then(i)}return p}function He(e,t,n){k(e,[t.localName,n])}var We=new Set(["click","dblclick","input","change","submit","keydown","keyup","mousedown","mouseup","pointerdown","pointerup"]),ze=11,De=["text","prop","prop","prop","prop","event","for","if","prop","radio","checkbox","prop","prop","event","spread"],Ue=(e,t,n,r)=>e.Xt(t,n.o?.t??n.St,r,De[n.i]),Fe=Symbol();function qe(e,t,n){let r=t.H;return null===r||"state"===r||"auto"===r&&void 0!==e.v(t.o,n)?t.V:Fe}var Be=class{constructor(e,t,n,r,i,s,o,l,a,u=null){this.Z=!1,this.I=null,this.attribute=null,this.$n=!1,this.engine=e,this.i=t,this.a=n,this.name=r,this.o=i,this.r=s,this.En=o,this.N=l,this.value=a,this.M=u}en(){return De[this.i]}apply(){if(null!==this.M)return void this.M.bt();let e=Ne(this.N,this.engine.read(this.o,this.r));if(e===this.value&&("object"!=typeof e||null===e||this.i===ze||8===this.i||xe(this.name)))return;if(this.value===Fe)return void(this.value=e);let t=this.a;if(this.i!==ze)9===this.i?t.checked=void 0!==e&&this.nn()===e:10===this.i?t.checked=Array.isArray(e)&&e.includes(this.nn()):Ge(this.i,t,this.name,e),this.value=e;else{if(void 0===e)return void(this.value=e);this.value=e,this.$n=!0;try{t[this.name]!==e&&(t[this.name]=e)}finally{this.$n=!1}null!==this.attribute&&function(e,t,n){try{if(null==n)e.removeAttribute(t);else{let r=n;if("object"==typeof n)try{r=JSON.stringify(n)}catch{}e.setAttribute(t,String(r))}}catch{}}(t,this.attribute,e)}}nn(){return Ne(this.I,this.a.value)}Xo(){let e,t=this.a,n=this.engine;if(9===this.i){if(!t.checked)return;e=this.nn()}else if(10===this.i){let r=this.nn(),i=n.v(this.o,this.r),s=Array.isArray(i)?i:[],o=s.includes(r);if(t.checked?o:!o)return;e=o?s.filter(e=>e!==r):[...s,r]}else e=Ne(this.I,t[this.name]);n.P(this.o,this.r,e,!1,!0)}},Ke=e=>"textContent"===e||"innerText"===e||"innerHTML"===e;function Ge(e,t,n,r){switch(e){case 0:return void(t.data=null==r?"":String(r));case 1:return void(Ke(n)?t[n]="innerHTML"===n?Te(r):null==r?"":String(r):xe(n)?null==r&&"srcdoc"===n?t.removeAttribute(n):void 0!==r&&(t[n]=Te(r)):void 0!==r&&(t[n]!==r&&!("value"===n&&t.value===String(r))&&(t[n]=r),("value"===n||"selectedIndex"===n)&&"select"===t.localName&&(t[Ve]=[n,r])));case 8:return void(t.innerHTML=Te(r));case 2:return null!=r&&"boolean"!=typeof r&&k(401,[n,typeof r]),void t.classList.toggle(n,!0===r);case 3:return void(null==r?t.removeAttribute(n):t.setAttribute(n,String(r)));case 4:return void(null==r?t.style.removeProperty(n):t.style.setProperty(n,String(r)))}}var Ve=Symbol();function Je(e){let t="optgroup"===e.localName?e.parentNode:e,n=t?.[Ve];void 0!==n&&(t[n[0]]=n[1])}var Qe=class{constructor(e,t,n,r){this.y=!0,this.fe=null,this.h=null,this.kt=null,this.xn=null,this.r=e,this.Ue=t,this.j=n,this.A=r}Vo(e,t){let n=t.target,r=this.A,i=[],s=null;for(let t of r.Ne){if(t.name!==e)continue;let o=r.Rn[t.a],l=at(null===this.j?this.Ue:this.j[o[0]],o,1);l.contains(n)&&(l!==s&&i.unshift([]),i[0].push(t),s=l)}for(let e of i){for(let n of e)n.Nn(t,this.r);if(t.cancelBubble)return!0}return!1}get s(){return null===this.j?this.Ue:this.j[this.j.length-1]}qe(){let e=this.xn;return(null===e?null:e.Pn(this.Ue))??this.Ue}insertBefore(e,t){let n=this.s;for(let r=this.qe();;){let i=r.nextSibling;if(e.insertBefore(r,t),r===n)return;r=i}}uo(){null===this.j?this.Ue.remove():ut(this.qe(),this.s)}Se(e){if(this.y=!1,null!==this.kt)for(let e of this.kt)e();let t=this.fe;if(null!==t)for(let n=0;n<t.length;n++)e.kn(t[n]);if(null!==this.h)for(let e of this.h)e.Se()}},Xe=class extends Qe{constructor(e,t,n,r){super(e,t,n,r),this.fo=0,this.W=null,this.ae=0===r.Ke.length?null:new Array(2*r.Ke.length)}po(e,t){let n=this.W??=new Array(this.A.Ke.length),r=n[t];if(void 0===r){let i=this.A.Ke[t],s=this.ae;r=n[t]=new Be(e,i.i,s[2*t],i.name,i.o,this.r,this,i.N,s[2*t+1])}return r}no(e,t){let n=this.A.Ke;for(let r=0;r<n.length;r++)n[r].o.Q(t)&&e.Qt(this.po(e,r))}Se(e){let t=this.r;t.$===this&&(t.$=null),super.Se(e)}};function Ye(e,t,n,r){let i=ee(n,t.n);try{return e.De(i,t)}catch(n){return e.Xt(n,t.t,r,"for"),null===i?e.ee.get(t):i.h.get(t)}}function Ze(e,t,n){n&&e.zo(t);let r=t.En;null!==r&&(r.fe??=[]).push(t)}var et=null;function tt(){let e=et;return et=null,e}var nt=-1;function rt(e,t,n,r,i=null){let s,o=t.Rn,l=t.build,a=t.mo,u=null,h=c.Ae?.(t,null===r?i:r.S,null!==r),d=!h&&t.Tn,f=h?document.createDocumentFragment():(d?t.root:t.on).cloneNode(!0);if(!h)for(let e=0;e<l.length;e++){let t=l[e];a[t]=at(f,o[t],d?1:0)}d?s=f:(u=h||[...f.childNodes],s=u[0]);let p,m=null;if(null!==r?(p=m=new Xe(n,s,u,t),null===r.map?n.$=m:r.map.set(n,m)):p=new Qe(n,s,u,t),nt>=0&&function(e,t,n,r){let i=null;if(null===t)i=1===e.nodeType?e:null;else for(let e=0;e<t.length&&null===i;e++)1===t[e].nodeType&&(i=t[e]);let s=i?.style;if(null===i||void 0===s||Oe.has(i))return;let o=globalThis[Pe]??={counter:0,assigned:0,warned:!1};o.assigned>=r?o.warned||(o.warned=!0,console.warn(`[@wcstack/state] ${$(25,[r])}`)):(Oe.add(i),o.assigned++,s.setProperty("view-transition-name",`wcs-${n}-${++o.counter}`),s.setProperty("view-transition-class",`wcs-${n}`))}(s,u,null!==r?"row":"branch",nt),t.Ne.length>0){let t=e.Dn;if(null===u)s[t]=p;else for(let e of u)1===e.nodeType&&(e[t]=p)}let g=t.Yo,y=e.Ie,b=t.Go?a.slice(0,o.length):a,v=null===m?null:m.ae;if(null!==v){let e=t.Ke;for(let t=0;t<e.length;t++)v[2*t]=b[e[t].a],v[2*t+1]=e[t].V}for(let r=0;r<g.length;r++){let i=g[r],o=b[i.a],l=i.F;if(l>=0&&null!==v){let r=m.W?.[l];if(void 0!==r){r.Z=!1,e._e(r);continue}try{let t=Ne(i.N,e.read(i.o,n));t!==i.V&&(Ge(i.i,o,i.name,t),v[2*l+1]=t),null!==y&&e.io(i.o,n)}catch(t){e.vt(t,m.po(e,l))}continue}switch(i.i){case 6:{let t=new lt(e,i.A,Ye(e,i.o,n,o),o);(p.h??=[]).push(t),o===s&&(p.xn=t),t.bt();break}case 7:{let t=st(e,i.X.map(e=>({A:e.A,o:e.o,N:e.N,S:b[e.a]})),n,p);(p.h??=[]).push(t),o===s&&(p.xn=t);break}default:try{it(e,i,o,n,p)}catch(t){Ue(e,t,i,o)}}}return et=p,f}function it(e,t,n,r,i){let s=n;switch(t.i){case 5:return void function(e,t,n,r,i){let s=n.Nn,o=e=>s(e,r);if(n.Ze){let r=e.eo(n.name),i=t[r];t[r]=void 0===i?o:e=>{i(e),o(e)},n.ke&&t.addEventListener(n.name,e=>e.bubbles||o(e))}else t.addEventListener(n.name,o),n.co&&null!==i&&(i.kt??=[]).push(()=>t.removeEventListener(n.name,o))}(e,n,t,r,i);case 12:return void je(e,t,s,i,n=>function(e,t,n,r,i){let s=t.name,o=e.command(t.St.slice(9));null===i&&He(1202,n,`command.${s}`),i.commands.has(s)||k(1203,[n.localName,s]);let l=new WeakRef(n),a=o.subscribe((...e)=>{let t=l.deref();if(void 0!==t)return t.isConnected?t[s](...e):void 0;a()});null!==r&&(r.kt??=[]).push(a)}(e,t,s,i,n));case 13:return void je(e,t,s,i,n=>function(e,t,n,r,i){let s=t.name;null===i&&He(1202,n,`eventToken.${s}`);let o=i.properties.get(s);void 0===o&&k(1204,[n.localName,s]);let l=t.St;n.addEventListener(o.event,n=>{t.Et&&n.preventDefault(),t.$t&&n.stopPropagation();try{e.Uo(l,n,r)}catch(e){console.error(e)}})}(e,t,s,r,n))}let o=t.o,l=ee(r,o.n);if(14===t.i)return void je(e,t,s,i,n=>function(e,t,n,r,i,s){null===s&&He(1501,n,`"...: ${t.o.t}"`);let o=new Set([...s.properties.keys(),...s.inputs.keys()]);for(let l of o){if(t.ao?.includes(l))continue;let o=e.o(`${t.o.t}.${l}`),a=0===o.n?null:r;Re(e,{...t,H:null,z:null},n,l,o,a,i,s)}}(e,t,s,l,i,n));if(t.ke&&1===t.i)return void je(e,t,s,i,n=>function(e,t,n,r,i,s){if(null!==s)return void Re(e,t,n,t.name,t.o,r,i,s);let o=new Be(e,1,n,t.name,t.o,r,i,t.N,qe(e,t,r));o.I=t.I,!c.Jo?.(o,t.ro)&&(Ze(e,o,!0),e._e(o))}(e,t,s,l,i,n));let a=new Be(e,t.i,n,t.name,o,l,i,t.N,qe(e,t,l));a.I=t.I,Ze(e,a,!0),e._e(a),null!==t.Nt&&n.addEventListener(t.Nt,()=>a.Xo())}function st(e,t,n,r){let i=new ot(e,t,n),s=null;for(let o of t){if(null===o.o)continue;let t=o.o,l=new Be(e,7,o.S,"if",t,ee(n,t.n),r,null,void 0,i);Ze(e,l,!0),null===r&&i.ie.push(l),s??=l}return e._e(s),i}var ot=class{constructor(e,t,n){this.y=!0,this.O=null,this.b=-1,this.ie=[],this.engine=e,this.X=t,this.r=n}Pn(e){return null!==this.O&&this.X[this.b].S===e?this.O.qe():null}bt(){let e=this.engine,t=-1;for(let n=0;n<this.X.length;n++){let r=this.X[n];if(null===r.o||Ne(r.N,e.read(r.o,ee(this.r,r.o.n)))){t=n;break}}if(t!==this.b&&(nt=Me(),null!==this.O&&(this.O.uo(),this.O.Se(e),this.O=null),this.b=t,t>=0)){let n=this.X[t],r=rt(e,n.A,this.r,null,n.S);this.O=tt();let i=n.S.parentNode;i.insertBefore(r,n.S),Je(i)}}Se(){this.y=!1;for(let e of this.ie)this.engine.kn(e);null!==this.O&&this.O.Se(this.engine)}},lt=class{constructor(e,t,n,r){this.y=!0,this.Ee=[],this.engine=e,this.A=t,this.l=n,this.S=r,null===n.$?(n.$=this,this.map=null):((n.L??=[]).push(this),this.map=new Map)}Pn(e){return 0===this.Ee.length?null:this.Ee[0].qe()}xt(e){return null===this.map?e.$:this.map.get(e)??null}ho(e){let t=this.map;null!==t&&t.get(e.r)===e&&t.delete(e.r),e.Se(this.engine)}bt(){let e=this.engine,t=this.l.u,n=this.Ee;nt=Me();let r=t.length,i=n.length,s=this.S,o=s.parentNode;if(0===r){if(i>0){ut(n[0].qe(),n[i-1].s);for(let e=0;e<i;e++)this.ho(n[e])}return void(this.Ee=[])}let l=new Array(r),a=0;for(;a<r&&a<i&&this.xt(t[a])===n[a];)l[a]=n[a],a++;let u=i-1,c=r-1;for(;u>=a&&c>=a&&this.xt(t[c])===n[u];)l[c]=n[u],u--,c--;for(let e=a;e<=u;e++){let t=n[e],r=t.r;r.y&&this.xt(r)===t?t.fo=e:(t.uo(),this.ho(t))}if(a<=c){let n=c-a+1,u=new Int32Array(n),h=!1;if(i>0)for(let e=0;e<n;e++){let n=this.xt(t[a+e]);null!==n&&n.y?(u[e]=n.fo,h=!0):u[e]=-1}let d=c+1<r?l[c+1].qe():s;if(h){let r=function(e){let t=e.length,n=new Uint8Array(t),r=new Int32Array(t).fill(-1),i=[];for(let n=0;n<t;n++){let t=e[n];if(t<0)continue;let s=0,o=i.length;for(;s<o;){let n=s+o>>1;e[i[n]]<t?s=n+1:o=n}s>0&&(r[n]=i[s-1]),i[s]=n}let s=i.length>0?i[i.length-1]:-1;for(;s>=0;)n[s]=1,s=r[s];return n}(u),i=d;for(let s=n-1;s>=0;s--){let n=t[a+s],u=this.xt(n);null!==u&&u.y?0===r[s]&&u.insertBefore(o,i):(o.insertBefore(rt(e,this.A,n,this),i),u=tt()),l[a+s]=u,i=u.qe()}}else{let n=document.createDocumentFragment();for(let r=a;r<=c;r++)n.appendChild(rt(e,this.A,t[r],this)),l[r]=tt();o.insertBefore(n,d)}}this.Ee=l,Je(o)}Se(){this.y=!1;let e=this.l;if(e.$===this)e.$=null;else if(null!==e.L){let t=e.L.indexOf(this);t>=0&&e.L.splice(t,1),0===e.L.length&&(e.L=null)}for(let e of this.Ee)e.Se(this.engine);this.map?.clear()}};function at(e,t,n){for(;n<t.length;n++){e=e.firstChild;for(let r=t[n];r>0;r--)e=e.nextSibling}return e}function ut(e,t){let n=document.createRange();n.setStartBefore(e),n.setEndAfter(t),n.deleteContents()}var ct=()=>re.bindAttributeName;function ht(){return{a:0,i:1,name:"",o:null,N:null,V:t,Nn:null,A:null,X:null,I:null,Nt:null,ke:!1,H:null,z:null,ro:!1,Et:!1,$t:!1,St:null,ao:null,F:-1,Ze:!1,co:!1}}var dt=["state","element","auto","none"],ft=["call","connect"],pt="$command.";function mt(e,t,n){P.test(t)&&(null===n&&k(1401,[t,Number(t.slice(1))]),t=`${n.t}.*.${t}`);let r=e.o(function(e,t){return 46!==e.charCodeAt(0)?e:(null===t&&k(1402,[e]),"."===e?`${t.t}.*`:`${t.t}.*${e}`)}(t,n)),i=null===n?0:n.n+1;r.n>i&&k(1401,[r.t,r.n,i]);for(let e=1;e<=r.n;e++){let t=e===i?n:n.f[e];r.f[e]!==t&&k(1403,[r.t,r.f[e].t,t.t])}return c.go?.(e,r),r}var gt=e=>1===e.i&&("outerHTML"===e.name||"outerText"===e.name),yt=e=>8===e.i||gt(e)||1===e.i&&Ke(e.name);function bt(e){k(202,[e])}function vt(e,t,n,r,i){let s=ae(t).map(t=>function(e,t,n,r,i){let s=function(e,t){let n=t.find(e=>e.startsWith("on")),r=null,i=null;for(let n of t){let t=n.indexOf("=");if(t<0)continue;e.Dt||k(31);let s=n.slice(0,t).trim(),o=n.slice(t+1).trim(),l="init"===s;!l&&"sync"!==s&&k(33,[s,n]),null!==(l?r:i)&&k(34,[s]),(l?dt:ft).includes(o)||k(35,[s,o]),l?r=o:i=o}return{ro:t.includes("ro"),Et:t.includes("prevent"),$t:t.includes("stop"),event:n?n.slice(2):null,H:r,z:i}}(e,t.tn),o=r.localName.includes("-"),l=t.ve,a=t.Je;if("event"===t.w){if(null!==s.H&&"none"!==s.H&&k(36),"eventToken"===l[0])return{...ht(),a:i,i:13,name:l.slice(1).join("."),St:a,ke:o,Et:s.Et,$t:s.$t};let n=a.startsWith(pt)?a.slice(9):null,{Et:r,$t:u}=s,c=t.be.slice(2),h=t.tn.includes("direct"),d=!h&&We.has(c);return d&&e.eo(c),{...ht(),a:i,i:5,name:c,Ze:d,ke:o,co:h,Nn(t,i){r&&t.preventDefault(),u&&t.stopPropagation();try{if(null!==n)e.qo(n,t,i);else{let n=e.Ko(a,t,i);Q(n)&&n.then(void 0,e=>console.error(e))}}catch(e){console.error(e)}}}}if("spread"===t.w)return{...ht(),a:i,i:14,o:mt(e,a,n),ke:o};if("command"===l[0]&&l.length>1)return a.startsWith(pt)||k(1201,[t.be,a]),{...ht(),a:i,i:12,name:l.slice(1).join("."),St:a,ke:o};let u=mt(e,a,n),c={...ht(),a:i,i:1,name:t.be,o:u,N:Ae(t.Qe),I:Ae(t.I),ro:s.ro,H:s.H,z:s.z};if("radio"===t.w||"checkbox"===t.w)return("element"===s.H||"auto"===s.H)&&k(37,[t.w,s.H]),c.i="radio"===t.w?9:10,s.ro||(c.Nt=s.event??"input"),c;if(l.length>1){let e=l.slice(1).join("."),t=l[0];if("class"===t||"attr"===t||"style"===t)return c.H=null,c.name=e,"class"===t?(c.i=2,c.V=r.classList.contains(e)):c.i="attr"===t?"srcdoc"===e&&"iframe"===r.localName?1:3:4,c}return"html"===t.be?(c.i=8,c):(c.name="text"===t.be?"textContent":t.be,c.ke=o&&!xe(c.name),!o&&!s.ro&&function(e,t){let n=e.localName;if("input"===n){let n=(e.getAttribute("type")||"text").toLowerCase();return"button"!==n&&(("radio"===n||"checkbox"===n)&&"checked"===t||"value"===t||"valueAsNumber"===t||"valueAsDate"===t)}return("select"===n||"textarea"===n)&&"value"===t}(r,c.name)&&(c.Nt=s.event??("select"===r.localName?"change":"input")),c)}(e,t,n,r,i));for(let e=0;e<s.length;e++)14===s[e].i&&(s[e].ao=s.slice(e+1).filter(e=>1===e.i).map(e=>e.name));return s}var wt=/\{\{([\s\S]+?)\}\}/g;function _t(e){let t=e.data,n=[],r=0;wt.lastIndex=0;for(let i=wt.exec(t);null!==i;i=wt.exec(t)){let s=wt.lastIndex-i[0].length;s>r&&e.before(t.slice(r,s));let o=e.ownerDocument.createTextNode("");e.before(o),n.push({a:o,Qo:i[1].trim()}),r=wt.lastIndex}return 0===n.length||(r<t.length&&e.before(t.slice(r)),e.remove()),n}function $t(e,t,n,r){let i=function(e){return{be:"textContent",ve:["textContent"],tn:[],I:[],...D(e),w:"text"}}(t);return{...ht(),a:r,i:0,o:mt(e,i.Je,n),N:Ae(i.Qe),V:""}}function kt(e){let t=e.getAttribute(ct());if(null===t)return null;let n=ae(t)[0];return void 0===n||"for"!==n.w&&"if"!==n.w&&"elseif"!==n.w&&"else"!==n.w?null:n}var St=(e,t)=>0===e?re.commentIfPrefix:null===t.o?re.commentElsePrefix:re.commentElseIfPrefix;function Nt(e,t,n){let r=(t,r)=>({el:t,o:"else"===r.w?null:mt(e,r.Je,n),N:"else"===r.w?null:Ae(r.Qe)}),i=[r(t,kt(t))];for(let e=t.nextSibling;null!==e;e=e.nextSibling){if(3===e.nodeType&&""===e.data.trim()||8===e.nodeType)continue;if(1!==e.nodeType||"template"!==e.localName)break;let t=kt(e);if(null===t||"elseif"!==t.w&&"else"!==t.w||(i.push(r(e,t)),"else"===t.w))break}return i}var At=new WeakSet;function Et(e,t,n,r,i,s,o,l){let a=(t,n)=>{let i=document.createComment(n);return t.replaceWith(i),r&&c.An?.(e,i,t),i},u=t=>{for(let h=0;h<t.length;h++){let d=t[h];if(null!==d.parentNode)if(1===d.nodeType){let t=d,l=t.localName;if(r){if("script"===l||"style"===l||At.has(t))continue;if(At.add(t),l===re.tagNames.state){u([...t.childNodes]);continue}}let h="template"===l?kt(t):null;if(null!==h){if("for"===h.w){let r=mt(e,h.Je,n),s=Tt(e,t,r,!0);i(a(t,re.commentForPrefix),r,s)}else"if"===h.w?s(Nt(e,t,n).map((t,r)=>({A:Tt(e,t.el,n,!1),o:t.o,N:t.N,S:a(t.el,St(r,t))}))):bt(h.w);continue}let f=t.getAttribute(ct()),p=null===f?null:vt(e,f,n,t,0),m="noscript"!==l&&"iframe"!==l&&!p?.some(yt)&&!c.yo?.(t);try{r&&m&&u([...t.childNodes])}finally{null!==p&&o(t,p)}!r&&m&&u([...t.childNodes])}else if(3===d.nodeType&&e.Lt&&d.data.includes("{{")&&!At.has(d))for(let{a:e,Qo:t}of _t(d))l(e,t);else if(8===d.nodeType){let e=Ct.exec(d.data),t=e&&d.parentNode.localName;if(null!==t&&"textarea"!==t&&"title"!==t){let t=document.createTextNode("");d.replaceWith(t),l(t,e[1])}}}};u(t)}var Ct=/^\s*@@\s*(?:wcs-text)?\s*:\s*([\s\S]+?)\s*$/,xt=e=>{let t=document.createRange();return t.selectNodeContents(e),e.content??t.cloneContents()};function Tt(e,t,n,r){let i=document.importNode(xt(t),!0),s=[],o=[],l=e=>s.push(e)-1;Et(e,[...i.childNodes],n,!1,(e,t,n)=>{o.push({...ht(),a:l(e),i:6,o:t,A:n})},e=>{let t=e.map(e=>({a:l(e.S),A:e.A,o:e.o,N:e.N}));o.push({...ht(),a:t[0].a,i:7,X:t})},(e,t)=>{let n=l(e);for(let e of t)gt(e)&&k(203,[e.name]),e.a=n;o.push(...t),e.removeAttribute(ct())},(t,r)=>{o.push($t(e,r,n,l(t)))}),Lt(i,new Set(s),!0);let a=s.map(e=>function(e,t){let n=[];for(let r=t;r!==e;r=r.parentNode){let e=0;for(let t=r.previousSibling;null!==t;t=t.previousSibling)e++;n.unshift(e)}return n}(i,e)),u=1===i.childNodes.length&&8!==i.firstChild.nodeType,c=o.some(e=>6===e.i||7===e.i),h=[],d=new Set,f=[],p=[],m=r?n.n+1:-1;for(let e of o){if(5===e.i&&e.Ze&&!e.ke&&!Pt(s[e.a],i)){f.push(e);continue}p.push(e);let t=e.o;if(null!==t&&t.n===m&&t.f[m]===n&&Ot(e)&&(e.F=h.push(e)-1),7===e.i)for(let t of e.X)d.add(t.a);else d.add(e.a)}let g=[...d].sort((e,t)=>e-t);return{on:i,root:u?i.firstChild:null,Rn:a,build:g,Ne:f,Yo:p,Tn:u,Go:c,mo:[],Ke:h}}function Pt(e,t){for(;e.parentNode!==t;e=e.parentNode){if(e.parentNode.localName.includes("-"))return!0;for(let t=e.previousSibling;t;t=t.previousSibling)if(8===t.nodeType)return!0}return!1}function Ot(e){if(null!==e.H)return!1;switch(e.i){case 0:case 2:case 3:case 4:case 8:return!0;case 1:return!e.ke&&null===e.Nt;default:return!1}}var Mt=new Set(["table","thead","tbody","tfoot","tr","colgroup","select","optgroup","datalist"]);function Lt(e,t,n){for(let r=e.firstChild;null!==r;){let e=r.nextSibling;3===r.nodeType?n&&!t.has(r)&&""===r.data.trim()&&r.remove():1===r.nodeType&&Lt(r,t,Mt.has(r.localName)),r=e}}var It=new WeakMap;function jt(e,t){let n=9===t.nodeType?t.body:t;e.root=t,It.set(t,e),Ht(e,[...n.childNodes]),e.He()}function Rt(e,t,n){try{let r="template"===t.localName?kt(t):null;null!==r&&!n&&k(204,[r.w]),Ht(e,[t])}catch(e){console.error(e)}e.He()}function Ht(e,t){Et(e,t,null,!0,(t,n,r)=>{new lt(e,r,Ye(e,n,null,t),t).bt()},t=>{st(e,t,null,null)},(t,n)=>{c.An?.(e,t,n);for(let r of n)it(e,r,t,null,null)},(t,n)=>{c.An?.(e,t,n),it(e,$t(e,n,null,0),t,null,null)})}var Wt=Symbol.for("wcstack.binder"),zt=Symbol.for("wcstack.binder.pending"),Dt=Symbol.for("wcstack.binder.taken"),Ut=new Map;function Ft(e,t){if(1!==e.nodeType||!e.isConnected)return;let n=It.get(e.getRootNode());void 0===n||!1===n.element?.isConnected?Ut.set(e,t):Rt(n,e,t?.range)}function qt(){let e=[...Ut];Ut.clear();for(let[t,n]of e)Ft(t,n);!function(){let e=function(){let e=globalThis[Wt];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}();if(null===e)return;let t=function(){let e=globalThis,t=e[zt];return void 0===t&&(t=[],e[zt]=t),t}();if(0===t.length)return;let n=t.splice(0,t.length),r=function(){let e=globalThis,t=e[Dt];return void 0===t&&(t=new WeakSet,e[Dt]=t),t}();for(let t of n)r.add(t),e.bind(t)}()}var Bt=class{constructor(){this.name="dirty",this.ot=(e,r)=>{if(0===e.n){let r=e.J;return r!==t&&r!==n&&(e.J=n,!0)}let i=null===r?null:r.ut;if(null===i)return!1;let s=i[e.F];return s!==t&&s!==n&&(i[e.F]=n,!0)}}Ho(e,t,n){null!==t.getter&&this.ot(t,n),e.wt(t,n),e.vn(t,n,this.ot)}Lo(e,t){let n=t.l.o.Tt;if(null!==n)for(let r of n)r.n===t.l.n?e.tt(r,t,this.ot):e.Jt(t,r,t=>e.tt(r,t,this.ot))}me(e,t,n){this.ot(t,n),c.ye?.(e,t,n),e.wt(t,n),e.vn(t,n,this.ot)}Bo(e,i,s){let o=0===i.n;if(!o&&null===s)return;let l=o?null:s.ut??=new Array(e.Oe).fill(t),a=null===l?i.J:l[i.F];if(a!==t&&a!==n&&a!==r&&(null===l||i.F in l))return a;a=r;try{return a=e.Do(i,null===l?null:s)}finally{null===l?i.J=a:l[i.F]=a}}qt(e){e.ut=null}pt(e){for(let t of e.B.all())null!==t.getter&&(0===t.n?t.J===n&&(t.J=r):e.Zt(t.f[t.n],e=>{let i=e.ut;null!==i&&i[t.F]===n&&(i[t.F]=r)}))}},Kt=0,Gt=new WeakMap;function Vt(e,t=e.getRootNode()){Gt.set(t,[...Gt.get(t)??[],e].filter((e,t,n)=>e.isConnected&&n.lastIndexOf(e)===t))}function Jt(e){let t=Gt.get(e)??[],n=t.filter(t=>t.getRootNode()===e);return Promise.any(n.map(e=>e.initializePromise.then(()=>e.W||e.connectedCallbackPromise))).then(()=>{},r=>n.length?Gt.get(e)!==t?Jt(e):Promise.reject(r.errors[0]):void 0)}var Qt=typeof HTMLElement>"u"?class{}:HTMLElement,Xt=class extends Qt{constructor(){super(),this.engine=null,this.Fn=!1,this.Ve=!1,this.V=null,this.ze=null,this.loaded=!1,this.ln=null,this.connectedCallbackPromise=new Promise((e,t)=>{this.sn=e,this.wo=t}),this.connectedCallbackPromise.catch(()=>{}),this.initializePromise=new Promise(e=>{this.rn=e})}static{this.getBindingsReady=Jt}static{this.hasConnectedCallbackPromise=!0}connectedCallback(){if(this.Fn){if(null!==this.ze)return void this.ze.Xe();Vt(this);let e=this.engine;if(null!==e){let t=e.root;t===this.getRootNode()&&!It.has(t)&&It.set(t,e),qt(),c.element?.(e,"back"),this.bo("$connectedCallback",50,()=>{this.isConnected&&c.element?.(e,"connected")})}return}this.Fn=!0;let e=this.getRootNode(),t=c.rt?.(this,e);if(t)return this.ze=t,!t.vo&&this.parentNode instanceof ShadowRoot&&Vt(this),void(void 0===t.jt?this.ko():t.jt()).then(e=>(this.loaded=!0,t.start(e,()=>this.So()))).then(()=>{this.rn(),this.sn()},e=>this.vt(e,t.vo));this.start(e),Vt(this)}disconnectedCallback(){if(null!==this.ze)return void this.ze.On();let e=this.engine;if(null===e)return;let t=e.root;It.get(t)===e&&It.delete(t),Vt(this,t),this.bo("$disconnectedCallback",51),c.element?.(e,"disconnected")}setInitialState(e){if(this.Ve&&k(14),this.loaded)this.ze.reset(e);else if(null===this.engine)if(null!==this.ln){let t=this.ln;this.ln=null,t(e)}else this.V=e;else this.engine.reset(e)}createState(e,t){let n=this.engine;null===n&&k(15),"readonly"===e&&n.Ce++;try{t(n.proxy)}finally{"readonly"===e&&n.Ce--}}async createStateAsync(e,t){let n=this.engine;null===n&&k(15),await t("writable"===e?n.proxy:new Proxy(n.proxy,{get(e,t,n){let r=Reflect.get(e,t,n);return"$setAll"===t||"$resolve"===t?(...e)=>(e.length>2&&k(8),r(...e)):r},set(){k(8)}}))}async ko(){await 0;let e=this.getAttribute("state");if(null!==e){let t=t=>[...t.querySelectorAll('script[type="application/json"]')].find(t=>t.id===e),n=t(this.getRootNode())??t(document);return void 0===n?Promise.reject(new Error(`[@wcstack/state] ${$(16,[e])}`)):Promise.resolve(JSON.parse(n.textContent||"{}"))}let t=this.getAttribute("src");if(null!==t)return async function(e){let t=new URL(e,document.baseURI).href;if(/\.json(?:[?#]|$)/.test(t)){let n=await fetch(t);return n.ok||k(13,[e,n.status]),await n.json()}return(await(import(t))).default??{}}(t);let n=this.getAttribute("json");if(null!==n)return Promise.resolve(JSON.parse(n));let r=this.querySelector('script[type="module"]');return null!==r?async function(e){let t=!1,n=e=>{e.effectiveDirective.startsWith("script-src")&&(t=!0)};document.addEventListener("securitypolicyviolation",n);let r="function"==typeof URL.createObjectURL,i=r?URL.createObjectURL(new Blob([e.text],{type:"application/javascript"})):"data:text/javascript;charset=utf-8,"+encodeURIComponent(`${e.text}\n//${++Kt}`);try{return(await(import(i))).default??{}}catch(e){throw await new Promise(e=>setTimeout(e)),new Error(`[@wcstack/state] ${t?$(42):$(43,[e instanceof Error?e.message:String(e)])}`,{cause:e})}finally{document.removeEventListener("securitypolicyviolation",n),r&&URL.revokeObjectURL(i)}}(r):null!==this.V?Promise.resolve(this.V):new Promise(e=>{this.ln=e})}async start(e){try{let t=e.host;(this.hasAttribute("mount")||this.hasAttribute("bind-component")||t?.hasAttribute("data-wc-definition"))&&b("scopes","<wcs-state>");let n=await this.ko(),r=y(n);if(r&&await r,this.getRootNode()!==e)return this.V=n,this.Fn=!1,void(this.isConnected&&this.connectedCallback());this.hasAttribute("enable-ssr")&&b("ssr","enable-ssr");let i=It.get(e)?.element;i?.isConnected&&(i.W||i.ze)&&k(47);let s=new ne(n,new Bt);s.element=this,this.engine=s,c.element?.(s,"mounting"),jt(s,e),qt(),s.bn(),this.So(),await s.we("$connectedCallback"),this.isConnected&&c.element?.(s,"connected"),this.sn()}catch(e){this.Ve=!this.W,this.vt(e)}}So(){this.W=!0,this.rn()}vt(e,t){this.He(this.W?50:49,e),this.rn(),t?this.sn():this.wo(e)}He(e,t){let n=["mount","bind-component","state","src"].flatMap(e=>this.hasAttribute(e)?[e,this.getAttribute(e)]:[]);console.error(`[@wcstack/state] ${$(e,[this.localName,...n])}`,t)}bo(e,t,n){(async()=>this.engine.we(e))().then(n,e=>this.He(t,e))}},Yt=[];function Zt(){return(Yt=Yt.filter(e=>e.deref())).map(e=>e.deref())}var en,tn=e=>t=>{let n=e(t);return e=>null==e?e:n(e)},nn="en";function rn(){if(re.locale!==en){en=re.locale;try{nn=Intl.getCanonicalLocales(en)[0]}catch{console.warn(`[@wcstack/state] ${$(48,[en])}`),nn="en"}}return nn}var sn={toFixed:{factory:e=>{let t=ve(e?.[0]??"0","toFixed");return e=>("number"!=typeof e&&ge("toFixed"),e.toFixed(t))},arity:[0,1]},locale:{factory:e=>{let t=e?.[0];return e=>("number"!=typeof e&&ge("locale"),e.toLocaleString(t??rn()))},arity:[0,1]},upper:{factory:tn(()=>e=>String(e).toUpperCase()),arity:[0,0]},lower:{factory:tn(()=>e=>String(e).toLowerCase()),arity:[0,0]},capitalize:{factory:tn(()=>e=>{let t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)}),arity:[0,0]},trim:{factory:tn(()=>e=>String(e).trim()),arity:[0,0]},slice:{factory:tn(e=>{let t=[we(e,0,"slice")],n=e?.[1];return typeof n<"u"&&t.push(ve(n,"slice")),e=>String(e).slice(...t)}),arity:[1,2]},padStart:{factory:tn(e=>{let t=we(e,0,"padStart"),n=e?.[1]??"0";return e=>String(e).padStart(t,n)}),arity:[1,2]},padEnd:{factory:tn(e=>{let t=we(e,0,"padEnd"),n=e?.[1]??" ";return e=>String(e).padEnd(t,n)}),arity:[1,2]},repeat:{factory:tn(e=>{let t=we(e,0,"repeat");return e=>String(e).repeat(t)}),arity:[1,1]},reverse:{factory:tn(()=>e=>String(e).split("").reverse().join("")),arity:[0,0]},truncate:{factory:tn(e=>{let t=we(e,0,"truncate"),n=e?.[1]??"…";return e=>{let r=String(e);return r.length<=t?r:r.slice(0,t)+n}}),arity:[1,2]},join:{factory:e=>{let t=e?.[0]??", ";return e=>(Array.isArray(e)||k(30,["join"]),e.join(t))},arity:[0,1]},round:{factory:e=>{let t=Math.pow(10,ve(e?.[0]??"0","round"));return e=>("number"!=typeof e&&ge("round"),Math.round(e*t)/t)},arity:[0,1]},floor:{factory:e=>{let t=Math.pow(10,ve(e?.[0]??"0","floor"));return e=>("number"!=typeof e&&ge("floor"),Math.floor(e*t)/t)},arity:[0,1]},ceil:{factory:e=>{let t=Math.pow(10,ve(e?.[0]??"0","ceil"));return e=>("number"!=typeof e&&ge("ceil"),Math.ceil(e*t)/t)},arity:[0,1]},percent:{factory:e=>{let t=ve(e?.[0]??"0","percent");return e=>("number"!=typeof e&&ge("percent"),`${(100*e).toFixed(t)}%`)},arity:[0,1]},unit:{factory:tn(e=>{let t=e?.[0]??pe("unit");return e=>String(e)+t}),arity:[1,1]},date:{factory:e=>{let t=e?.[0];return e=>(e instanceof Date||ye("date"),e.toLocaleDateString(t??rn()))},arity:[0,1]},time:{factory:e=>{let t=e?.[0];return e=>(e instanceof Date||ye("time"),e.toLocaleTimeString(t??rn()))},arity:[0,1]},datetime:{factory:e=>{let t=e?.[0];return e=>(e instanceof Date||ye("datetime"),e.toLocaleString(t??rn()))},arity:[0,1]},ymd:{factory:e=>{let t=e?.[0]??"-";return e=>{e instanceof Date||ye("ymd");let n=e.getFullYear().toString(),r=(e.getMonth()+1).toString().padStart(2,"0"),i=e.getDate().toString().padStart(2,"0");return`${n}${t}${r}${t}${i}`}},arity:[0,1]},hms:{factory:e=>{let t=e?.[0]??":";return e=>{e instanceof Date||ye("hms");let n=e.getHours().toString().padStart(2,"0"),r=e.getMinutes().toString().padStart(2,"0"),i=e.getSeconds().toString().padStart(2,"0");return`${n}${t}${r}${t}${i}`}},arity:[0,1]}},on=!1,ln={name:"formats",install:function(){on||(on=!0,de(sn))}};function an(e,t,n){if(Math.abs(e.length-t.length)>n)return n+1;let r=new Array(t.length+1),i=new Array(t.length+1);for(let e=0;e<=t.length;e++)r[e]=e;for(let n=1;n<=e.length;n++){i[0]=n;for(let s=1;s<=t.length;s++){let o=e[n-1]===t[s-1]?0:1;i[s]=Math.min(r[s]+1,i[s-1]+1,r[s-1]+o)}for(let e=0;e<=t.length;e++)r[e]=i[e]}return r[t.length]}function un(e,t){if(0===e.length)return"";let n=e.toLowerCase(),r=null,i=3;for(let e of t){let t=an(n,e.toLowerCase(),2);t<i&&(r=e,i=t)}return null!==r?` Did you mean "${r}"?`:""}var cn=" Validate statically: npx @wcstack/lint <file>.",hn=["enableMustache","sameValueGuard","enableDirectionalInitialSync"],dn=(e,t)=>`<${e}${t.map((e,t)=>t%2?`="${e}"`:` ${e}`).join("")}>`,fn="https://github.com/wcstack/wcstack/blob/main/docs/csp.md",pn={1:()=>"$scan was removed (use $watch or $on)",2:e=>`"${e}" is a getter without a setter`,3:e=>`no row for "${e}"`,4:(e,t)=>`cannot write "${e}": its parent is ${t}`,5:e=>`"${e}" is not a method`,6:e=>`$getAll("${e}"): no loop level in common with the context`,7:e=>`$eqIndex("${e}") needs a list row scope.`,8:()=>"This state is readonly.",9:e=>`$setAll("${e}") needs indexes ([] for every match)`,10:(e,t)=>`$setAll("${e}", …, { spread: true }) needs an array of ${t} values`,11:()=>"updates did not settle after 32 passes",41:()=>"render chain depth limit exceeded (100 drains that rendering itself started); bindings for this batch were not applied.",12:(e,t)=>`binding "${e}: ${t}" failed to apply.`,13:(e,t)=>`failed to load "${e}": ${t}`,14:()=>"this <wcs-state> failed to initialize; create a new one",15:()=>"state is not initialized",16:e=>`no <script> with id "${e}"`,42:()=>`The inline <script> of <wcs-state> was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/state, or allow blob: in script-src. Moving the state into an external file (src="./state.js") needs neither. See ${fn}`,43:e=>`Failed to evaluate the inline <script> of <wcs-state>: ${e}. If this page sets a Content-Security-Policy, see ${fn}`,17:e=>`a subscriber of token "${e}" threw.`,18:e=>`${e} must be an array of strings.`,19:e=>`${e} entries must be non-empty strings.`,20:(e,t,n)=>`${e} entry "${t}" conflicts with the reserved namespace name "${n}".`,21:(e,t)=>`${e} entry "${t}" is duplicated.`,22:()=>"$on must be an object of handlers.",23:e=>`$on entry "${e}" is not declared in $eventTokens.`,24:e=>`$on entry "${e}" must be a function.`,25:e=>`view-transition naming-limit (${e}) reached.`,26:e=>`filter ${e} requires at least one option`,27:e=>`filter ${e} requires a number as option`,28:e=>`filter ${e} requires a number value`,29:e=>`filter ${e} requires a date value`,30:e=>`filter ${e} requires an array value`,31:()=>"init=/sync= modifiers require enableDirectionalInitialSync.",33:(e,t)=>`Unknown binding modifier "${e}" in "${t}".`,34:e=>`Binding modifier "${e}" may only be specified once.`,35:(e,t)=>`Invalid ${e} modifier value "${t}".`,36:()=>"Event bindings only allow init=none.",37:(e,t)=>`Binding type "${e}" does not support init=${t}.`,38:e=>`Property "${e}" is not declared by wcBindable.`,39:(e,t)=>`init=${e} is incompatible with wcBindable member "${t}".`,40:e=>`sync=connect requires observable property "${e}".`,44:(e,t)=>`${e}: "${t}" is not one of its options, or not of the option's type.${"bootstrapState"===e&&hn.includes(t)?" 4.0 moved it to the state's $behavior.":""}`,45:()=>"a re-set state may not change $behavior: create the element again.",47:()=>'a second <wcs-state> on the same root: there is one state tree per root — graft a subtree with <wcs-state mount="path"> (v1\'s name="…" is gone: read the mounted state by its path).',48:e=>`the locale "${e}" (<html lang> or bootstrapState's locale) is not a language tag Intl takes (en-US, not en_US): the locale filters use "en".`,46:()=>'$features must be an array of add-on names (["temporal", "formats"]).',49:(e,...t)=>`${dn(e,t)} failed to initialize.`,50:(e,...t)=>`${dn(e,t)} $connectedCallback failed.`,51:(e,...t)=>`${dn(e,t)} $disconnectedCallback failed.`,101:e=>`Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.`,102:(e,t)=>`"${e}": "${t}" takes no modifiers or filters on its left side — write "${t}:".`,103:e=>`"${e}": "else" takes no value — write "else:".`,104:e=>`Invalid spread binding "${e}": spread target path is required.`,105:e=>`Invalid spread binding "${e}": filters are not allowed on spread targets.`,106:e=>`"${e}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (class, attr, style, command, eventToken, state).`,107:(e,t)=>`unterminated ${e} quote in the filter arguments "(${t})". Close the quote.`,108:e=>`Invalid filter format: missing closing parenthesis in "${e}".`,109:e=>`Invalid filter format: missing opening parenthesis in "${e}".`,110:e=>`Invalid filter format: ")" comes before "(" in "${e}".`,111:(e,t)=>`"${e}": unexpected "${t}" after the filter's closing ")" — separate filters with "|" (write "${e.slice(0,e.lastIndexOf(")")+1)}|${t}").`,112:e=>`an empty filter in "${e}" — remove the extra "|" or name the filter.`,113:(e,t)=>`"${e}" is not a filter name: a modifier list "#${t}" comes before the input filters, not inside one`,114:e=>`"${e}" is not a filter name: "#" cannot appear in one.`,115:e=>`"${e}": a binding takes one modifier list after a single "#"`,116:e=>`"${e}": the left side of a binding must name a property — write "<property>: <path>" (modifiers and input filters come after the name).`,117:(e,t)=>`"${e}" has ${t} path segments — the limit is 512.`,32:e=>`"${e}": 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.`,120:e=>`"${e}": a state path cannot go through "__proto__" or "prototype" (it would reach every object's prototype).`,121:e=>`"${e}": "for:" takes no filters — a row is "<path>.<index>", so the rows of a filtered list would name other elements. Declare a getter that returns the filtered list and loop over it ("for: <getter>").`,119:e=>`"${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).`,201:e=>`Invalid bindText: "${e}". 'if', 'elseif', 'else', and 'for' bindings must be single binding.`,202:e=>`"${e}:" must follow an "if:" template`,204:e=>`a "${e}:" template at the top of inserted content was not rendered, as it would render beside itself out of the inserter's reach: wrap it in an element.`,203:e=>`"${e}:" replaces its element, so it cannot be used inside a "for" / "if" template (a row or branch keeps its nodes by position): bind innerHTML: on a wrapper element instead.`,301:e=>`Path "${e}" does not exist on the state tree.`,401:(e,t)=>`class.${e} needs a boolean, got ${t}.`,501:e=>`filter not found: ${e}.`,601:(e,t,n)=>`filter "${e}" requires at least ${t} argument(s) (${n} given).`,602:(e,t,n)=>`filter "${e}" accepts at most ${t} argument(s) (${n} given).`,701:e=>`"${e}" depends on itself`,801:e=>`"${e}"`,901:(e,t,n,r)=>`${e}("${t}") takes ${n} index(es), got ${r}.`,902:(e,t,n,r)=>`${e}("${t}") takes at most ${n} index(es), got ${r}.`,1001:e=>`"${e}": list index parameters run from $1 to $128.`,1101:e=>`"${e}" uses "**", which is not accepted here.`,1201:(e,t)=>`"${e}: ${t}": the right-hand side must be $command.<name>`,1202:(e,t)=>`<${e}> declares no static wcBindable (${t}).`,1203:(e,t)=>`<${e}> declares no command "${t}".`,1204:(e,t)=>`<${e}> declares no property "${t}".`,1301:e=>`eventToken "${e}" is not declared in $eventTokens.`,1302:e=>`"$command.${e}" is not declared in $commandTokens.`,1401:(e,t,n=0)=>`"${e}" needs ${t} enclosing loop level(s); the scope provides ${n}.`,1402:e=>`"${e}" is relative: it needs an enclosing "for" template`,1403:(e,t,n)=>`"${e}" ranges over the rows of "${t}", but the enclosing "for" template at that level renders "${n}".`,1501:(e,t)=>`<${e}> declares no static wcBindable (${t}).`,1601:(e,t)=>`${e} was removed: write ${t}.`,1701:(e,t)=>`${e} was removed: write ${t}.`};function mn(e,t){let n=pn[e];return void 0===n?`${_(e)}#${e} ${t.join(" ")}`:_(e)+n(...t)}var gn=new Set(["binding-syntax","template-syntax","filter-unknown","filter-arity","index-arity","wildcard-rank","token-undeclared","binding-path-missing","index-param-range"]),yn=[[/no loop level in common with the context/,"; pass indexes ([] for all)."],[/"([^"#]+)#([^"]*)" is not a filter name: a modifier list .* comes before the input filters/,' — write "<property>#$2|$1".'],[/\[wcs\/recursion-unsupported\]/," 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."],[/must be single binding/,' Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).'],[/\[wcs\/wildcard-rank\] .* needs \d+ enclosing/,' Wrap it in that many "for" templates, or use $resolve(path, indexes) to name the row explicitly.'],[/\[wcs\/wildcard-rank\] .* ranges over the rows of/,' A "*" in a binding is the row of the loop around it: read a row of another list in a getter, with $resolve(path, indexes).'],[/\[wcs\/binding-type-expectation\] class\.([^ ]+)/,' Write "class.$1: path|truthy" to toggle on truthiness.'],[/path segments — the limit/," Every prefix of a path is interned, so the cost grows with the square of the depth."],[/\[wcs\/index-arity\] \$resolve/,' $resolve takes one index per "*"; $getAll / $setAll take at most that many (fewer expands the rest).'],[/"([^"#]+)#[^"]*" is not a filter name: "#" cannot appear in one/,' Modifiers belong on the left side of the binding, before the ":" — write "$1" here.']],bn={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function vn(e,t,n){let r=(void 0!==t&&e.includes("[wcs/filter-unknown]")?function(e){if("substr"===e)return' "substr" was removed in 4.0 — write slice(start, start + length): slice takes the end index, not a length.';let t=Object.hasOwn(bn,e)?bn[e]:null;return null===t?null:` "${e}" was renamed "${t}" in 3.2 and removed in 4.0 — write "${t}".`}(t):null)??(void 0!==t&&void 0!==n?un(t,n):"");for(let[t,n]of yn){let i=t.exec(e);null!==i&&(r+=n.replace(/\$(\d)/g,(e,t)=>i[Number(t)]))}let i=/"([^"#]+)#([^"]+)": a binding takes one modifier list/.exec(e);null!==i&&(r+=` — write "${i[1]}#${i[2].split("#").join(",")}".`),e.includes("[wcs/filter-unknown]")&&(e.includes("formats add-on")?r+=' On a split auto page: features="formats" on the root, or "$features": ["formats"].':ue.some(fe)||(r+=' No formatting filters are installed — add the formats add-on: installFeatures([formats]) from "@wcstack/state/features/formats" (a split auto page: features="formats", or "$features").'));let s=/\[wcs\/([\w-]+)\]/.exec(e);return null!==s&&gn.has(s[1])&&!/ path segments — the limit is |inserted content was not rendered|formats add-on/.test(e)&&(r+=cn),r}var wn=new WeakMap,_n=new WeakMap,$n=new WeakSet,kn=new WeakSet;function Sn(e,t){for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e}}function Nn(e){let t=new Set;for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n))for(let e of Object.getOwnPropertyNames(n))"$"!==e[0]&&"constructor"!==e&&t.add(e);return[...t]}function An(e,t){let n=[];for(let e=t;null!==e;e=e.d)n.unshift(e);let r=e.target,i=t=>null===t?null:function(e,t){let n=t.t.split("."),r=n.findIndex((e,t)=>t>0&&/^\d/.test(e));return r<0||n.indexOf("*",r)>=0||void 0!==Sn(e.target,t.t)?.get?t:e.B.Ot(o(t.t).o)}(e,t);for(let t of n){if(null!=i(t)?.getter||null===r||"object"!=typeof r)return null;if("*"===t.s){if(!Array.isArray(r)||0===r.length)return null;r=r[0];continue}if(Array.isArray(r)&&/^\d+$/.test(t.s)){if(Number(t.s)>=r.length)return null;r=r[Number(t.s)];continue}let n=Sn(r,t.s);if(void 0===n&&null===t.d&&e.pt.has(t.s))return null;if(void 0===n){let n=Nn(r),s=i(t.d);for(let t of e.B.all())t.d===s&&null!==t.getter&&n.push(t.s);return{seg:t.s,names:n}}if(void 0!==n.get||void 0!==n.set)return null;r=n.value}return null}function En(e){$n.has(e)||($n.add(e),setTimeout(()=>function(e){$n.delete(e);let t=wn.get(e);if(void 0===t)return;let n=_n.get(e);void 0===n&&_n.set(e,n=new Set);for(let[r,i]of t){if(n.has(r))continue;n.add(r);let t=An(e,r);if(null===t)continue;let s=[...e.root?.querySelectorAll(`${re.tagNames.state}[mount]`)??[]].find(e=>!kn.has(e)&&(r.t+".").startsWith(e.getAttribute("mount")+"."));if(void 0!==s){n.delete(r),s.initializePromise.then(()=>{kn.add(s),En(e)});continue}let[l,a]=i?["watch-path-missing","$watch path"]:["binding-path-missing","Bound path"];c.nt?.(e,{type:"state:path-unresolved",source:i?"watch":"binding",path:r.t,missingSegment:t.seg});let u=e.B.Ot(o(r.t).o),h="";if(void 0!==u&&u!==r&&null!==u.getter){let e=u.f.slice(1).map((e,t)=>`for: ${0===t?e.t:e.t.slice(u.f[t].t.length+2)}`);h=` The getter "${u.t}" is declared for the rows of ${e.join(" → ")}; a list named by an index has rows of its own.`}console.warn(`[@wcstack/state] [wcs/${l}] ${a} "${r.t}" does not resolve on the state tree: "${t.seg}" is not declared.${un(t.seg,t.names)}${h} Updates to this path will be silently dropped.${cn}`)}}(e),0))}function Cn(e,t,n=!1){if("$"===t.t[0]||t.t.includes("#")||!n&&null===t.d)return;let r=wn.get(e);void 0===r&&wn.set(e,r=new Map),r.has(t)||r.set(t,n),En(e)}var xn=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Tn=!1;function Pn(e,t,n){let r="html"===n.name?"innerHTML":n.name;if(Tn||!(t instanceof TypeError)||!xe(r)||!("trustedTypes"in globalThis))return;Tn=!0;let i="function"==typeof Ce()?.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 "${r}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${i}\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:n.a,property:r})}var On=new WeakMap;function Mn(e,t,n){let r=e[t],i=void 0===n?void 0===r?null:`the event carried no detail (undefined) while element.${t} is ${typeof r}`:null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,t)||null!==r&&"object"==typeof r?null:`the event's detail is an object with a "${t}" key while element.${t} is ${typeof r}`;if(null===i)return;let s=On.get(e);void 0===s&&On.set(e,s=new Set),!s.has(t)&&(s.add(t),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${e.localName}> "${t}": ${i}. 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.`))}var Ln={name:"diagnostics",install(){c.Ao=vn,c.Fo=mn,c.go=Cn,c.detail=Mn,c.Ve=h(c.Ve,Pn),c.se=h(c.se,(e,t)=>{(function(e){let t=e.$recursion;if(null===t||"object"!=typeof t)return;let n=Object.entries(t);if(1!==n.length||"string"!=typeof n[0][1])return;let[r,i]=n[0];if(!r.endsWith(".*")||!i.endsWith(".*"))return;let s=r.slice(0,-2),o=i.slice(0,-2),l=`.${i}`,a=`${s}.**`,u=Nn(e),c=u.filter(e=>e.startsWith(a)).map(e=>e.slice(a.length)),h=e=>v(`[wcs/recursion-declaration-invalid] ${e}`);for(let e of c){(e===`.${o}`||e.startsWith(`.${o}.`))&&h(`"${a}${e}" names the recursion structure itself (the "${o}" lists): recursive getters compute values over the nodes.`);for(let t of c)t.length>e.length&&t.endsWith(e)&&new RegExp(`^(?:${xn(l)})+$`).test(t.slice(0,t.length-e.length))&&h(`"${a}${e}" and "${a}${t}" expand to the same concrete path at different depths (they differ by whole repetitions of "${i}"). Rename one of them.`);let t=new RegExp(`^${xn(r)}(?:${xn(l)})*${xn(e)}$`);for(let n of u)!n.includes("**")&&t.test(n)&&h(`"${n}" is already defined on the state, so the recursive getter "${a}${e}" cannot expand to it.`)}})(t),function(e){_n.delete(e),wn.has(e)&&En(e)}(e)})}},In={},jn=/\.\d/,Rn=new Set(Object.getOwnPropertyNames(Object.prototype)),Hn=0,Wn=!1,zn=null,Dn=()=>{Wn=!1,Hn++};function Un(){if(null===zn)if("function"==typeof MessageChannel){let e=new MessageChannel;e.port1.onmessage=Dn,e.port1.unref?.(),zn=()=>e.port2.postMessage(0)}else zn=()=>setTimeout(Dn,0);return Wn||(Wn=!0,zn()),Hn}function Fn(e,t){let n=new Set,r=[e];for(;r.length>0;){let e=r.pop();if(!n.has(e)){n.add(e);for(let n of e.$e){for(let r of t)if(n.Q(r)&&(n.n===r.n||!(r.n<e.n&&e.f[r.n+1].Q(r))))return!0;null!==n.getter&&r.push(n)}}}return!1}var qn=class{constructor(e,t){this.active=!1,this.Ye=new Map,this.n=0,this.$o=-1,this.Cn=new Set,this.We=null,this.engine=e,this.it=t}Zo(){let e=this.engine;this.Ye.clear();for(let t of this.it)t.getter=null!==t.p.getter||t.p.de,t.s=new WeakMap,this.prime(t,()=>{0===t.p.n?t.getter&&t.s.set(In,e.v(t.p,null)):this.In(t.p,1,null,n=>{t.getter&&this.prime(t,()=>t.s.set(n,e.v(t.p,n)))})});this.active=!0}prime(e,t){try{t()}catch(t){console.error(`[@wcstack/state] $watch initial evaluation of "${e.t}" threw.`,t),c.nt?.(this.engine,{type:"state:watch-error",phase:"prime",path:e.t,error:t})}}No(){this.active=!1,this.Ye.clear()}In(e,t,n,r){let i=this.engine.De(n,e.f[t]);for(let n of i.u)t===e.n?r(n):this.In(e,t+1,n,r)}an(e,t,n,r){let i=this.Ye.get(e);void 0===i&&this.Ye.set(e,i=new Map);let s=i.get(t);void 0===s?i.set(t,[n,this.n,r]):(s[1]<this.n&&(s[1]=this.n),s[2]||=r)}he(e,t,n,r,i){if(this.active){(this.We??=new Set).add(e);for(let s of this.it){let o=s.p;o.n!==e.n||!o.Q(e)||this.an(s,t,s.getter?s.s.get(t??In):o===e&&i&&this.engine.Bt&&(null===r||"object"!=typeof r&&"function"!=typeof r)?n:void 0,!0)}}}ye(e,t){if(this.active)for(let n of this.it)(n.getter||=null!==n.p.getter||n.p.de)&&n.p.n===e.n&&n.p.Q(e)&&this.an(n,t,n.s.get(t??In),!1)}Yt(e,t){if(!this.active)return;let n=null;for(let r of this.it){let i=r.p;if(!(i.n<e.n||i.f[e.n]!==e.o)){n??=new Set(t);for(let t of e.u)n.has(t)||(i.n===e.n?this.an(r,t,void 0,!0):this.In(i,e.n+1,t,e=>this.an(r,e,void 0,!0)))}}}Te(){let e=this.We;if(this.We=null,!this.active||0===this.Ye.size)return;let t=this.Ye;this.Ye=new Map;let n=this.engine,r=[];for(let i of this.it){let s=t.get(i);if(void 0===s)continue;let o,l=[...s].filter(([e])=>null===e||e.y);l.length>1&&l.sort((e,t)=>Kn(e[0],t[0]));for(let[t,[s,a,u]]of l){let l,h="evaluate",d=n.c;this.n=a+1,n.xe++;try{if(l=n.v(i.p,t),i.getter&&(i.s.set(t??In,l),Object.is(l,s)&&(jn.test(i.t)||null!==t&&!u&&!(o??=null!==e&&Fn(Bn(i.p),e)))))continue;if(a>32){r.includes(i.t)||r.push(i.t);continue}n.c=t,c.nt?.(n,{type:"state:watch-fired",path:i.t}),h="handler",i.handler.call(n.proxy,l,s,...n._(t))}catch(e){console.error(`[@wcstack/state] $watch "${i.t}" failed; the other watches still run.`,e),c.nt?.(n,{type:"state:watch-error",phase:h,path:i.t,error:e})}finally{n.c=d,this.n=0,n.xe--}}}r.length>0&&this.xo(r)}xo(e){let t=Un();t!==this.$o&&(this.$o=t,this.Cn.clear());let n=e.filter(e=>!this.Cn.has(e));if(0!==n.length){for(let e of n)this.Cn.add(e);console.error("[@wcstack/state] $watch handlers / $stream restarts kept writing for 32 batches; the chain is cut (nothing is rolled back)."),c.nt?.(this.engine,{type:"state:watch-chain-limit",maxDepth:32,paths:n})}}};function Bn(e){for(;null===e.getter&&null!==e.d;)e=e.d;return e}function Kn(e,t){let n=[],r=[];for(let t=e;null!==t;t=t.l.re)n.unshift(t.b);for(let e=t;null!==e;e=e.l.re)r.unshift(e.b);for(let e=0;e<n.length&&e<r.length;e++)if(n[e]!==r[e])return n[e]-r[e];return n.length-r.length}var Gn="$streamStatus",Vn="$streamError",Jn=new Set(Object.getOwnPropertyNames(Object.prototype)),Qn=!1;function Xn(e,t){for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return void 0!==e.get||void 0!==e.set||"function"==typeof e.value}return!1}var Yn=class{constructor(e,t,n){this.engine=e,this.entries=t,this.D=n}set(e,t,n){Qn=!0;try{this.engine.P(this.engine.o(`${e}.${t}`),null,n)}finally{Qn=!1}}er(){for(let e of this.entries)this.start(e,!0)}tr(){for(let e of this.entries)e.st=!1,e.Y?.abort(),e.Y=null}nr(){for(let e of this.entries)e.st=!1,null!==e.Y&&(e.Y.abort(),e.Y=null),this.set(Gn,e.name,"idle")}ye(e){let t=this.D.n;for(let n of this.entries)n.g===e&&(n.n=n.st?Math.max(n.n,t):t,n.st=!0)}Te(){let e=this.engine,t=this.D,n=[];for(let i of this.entries){if(!i.st)continue;let s=i.n;if(i.st=!1,s>32)n.push(i.name),i.g.J=r;else{t.n=s+1,e.xe++;try{this.start(i,!1)}finally{e.xe--,t.n=0}}}n.length>0&&t.xo(n)}start(e,t){let n,i=this.engine;if(null!==e.Y&&e.Y.abort(),e.Y=null,null!==e.g){let s=e.g;s.getter=e.args;let o=s.$e.slice();Zn(s);try{n=i.read(s,null),function(e,t,n){null!==n&&"function"==typeof n?.then&&v(`$stream "${e}": args must be synchronous (it returned a Promise).`);for(let n of t.$e)n.n>0&&v(`$stream "${e}": args must not read a wildcard path ("${n.t}").`),(n.t===e||n.t===`${Gn}.${e}`||n.t===`${Vn}.${e}`)&&v(`$stream "${e}": args must not read the stream itself ("${n.t}").`)}(e.name,s,n)}catch(n){Zn(s);for(let e of o)e.jn(s);if(s.J=r,t)throw n;return this.set(Vn,e.name,n),void this.set(Gn,e.name,"error")}}let s=new AbortController;e.Y=s,i.P(i.o(e.name),null,e.V),this.set(Vn,e.name,null),this.set(Gn,e.name,"active"),this.or(e,s,n)}async or(e,t,n){let r=this.engine,i=t.signal,s=()=>!i.aborted&&e.Y===t,o=r.o(e.name),l=this.D.n,a=Un(),u=e=>{Un()===a&&(this.D.n=l);try{e()}finally{this.D.n=0}},c=e.V;try{let t=await e.source(n,i);if(!s())return;let l=t=>{c=void 0!==e.Ro?e.Ro(c,t):t,u(()=>r.P(o,null,c))};if(null!==t&&"function"==typeof t?.getReader){let e=t.getReader();for(i.addEventListener("abort",()=>{e.cancel().catch(()=>{})});;){let t=await e.read();if(!s())return;if(t.done)break;l(t.value)}}else{if(null===t||"function"!=typeof t?.[Symbol.asyncIterator])throw new TypeError(`$stream "${e.name}": source must return an async iterable or a ReadableStream`);{let e=t[Symbol.asyncIterator]();for(i.addEventListener("abort",()=>{e.return?.()});;){let t=await e.next();if(!s())return;if(t.done)break;l(t.value)}}}if(!s())return;e.Y=null,u(()=>this.set(Gn,e.name,"done"))}catch(n){if(!s())return;e.Y=null,t.abort(),u(()=>{this.set(Vn,e.name,n),this.set(Gn,e.name,"error")})}}};function Zn(e){for(let t of e.$e){let n=t.G.indexOf(e);n>=0&&t.G.splice(n,1),t.At.delete(e)}e.$e.length=0,e.J=t}var er=new WeakMap;function tr(e){let t=er.get(e);return t?.target===e.target?t:void 0}function nr(e,t){let n=new qn(e,function(e,t){if(void 0===t)return[];(null===t||"object"!=typeof t)&&v("$watch must be an object mapping paths to handler functions.");let n=[];for(let r of Object.keys(t)){let i=t[r];(""===r||"$"===r[0]||r.includes("@")||Rn.has(r))&&v(`$watch path "${r}" is not a path of the state tree.`),"function"!=typeof i&&v(`$watch entry "${r}" must be a function.`);let s=e.o(r);c.go?.(e,s,!0),n.push({t:r,p:s,handler:i,getter:!1,s:new WeakMap})}return n}(e,t.$watch)),r=new Yn(e,function(e,t){let n=t.$stream;if(void 0===n)return[];(null===n||"object"!=typeof n)&&v("$stream must be an object mapping stream names to definitions.");let r=[],i={},s={};for(let o of Object.keys(n)){let l=n[o];(""===o||"$"===o[0]||/[.*]/.test(o)||Jn.has(o))&&v(`$stream entry "${o}" must be a flat property name.`),(null===l||"object"!=typeof l)&&v(`$stream entry "${o}" must be an object.`);let a=l.source,u=l.fold,c=l.args,h=l.initial;"function"!=typeof a&&v(`$stream entry "${o}" needs a source function.`),void 0!==u&&"function"!=typeof u&&v(`$stream entry "${o}": fold must be a function.`),void 0!==u&&!("initial"in l)&&v(`$stream entry "${o}": fold needs an initial value.`),void 0!==c&&"function"!=typeof c&&v(`$stream entry "${o}": args must be a function.`),Xn(t,o)&&v(`$stream entry "${o}" collides with a getter, setter or method of the state.`),void 0===t[o]&&(t[o]=h),i[o]="idle",s[o]=null,r.push({name:o,source:a,Ro:u,V:h,Y:null,st:!1,n:0,g:void 0===c?null:e.o(`$streamArgs.${o}`),args:void 0===c?null:function(){return c(this)}})}return t[Gn]=i,t[Vn]=s,r}(e,t),n),i=er.get(e);void 0!==i&&(i.D.No(),i.Rt.tr()),er.set(e,{D:n,Rt:r,Xe:i?.Xe??!1,target:t})}function rr(e,t){let n=er.get(e);if(void 0!==n&&"mounting"!==t&&!document.documentElement?.hasAttribute("data-wcs-server")&&("reset"!==t&&(n.Xe="connected"===t),n.target===e.target)){if("disconnected"===t)return n.D.No(),void n.Rt.nr();n.Xe&&(n.D.Zo(),n.Rt.er())}}var ir=["$streamStatus","$streamError"],sr={name:"temporal",install(){c.se=h(c.se,nr),c.element=h(c.element,rr),c.he=h(c.he,(e,t,n,r,i,s)=>tr(e)?.D.he(t,n,r,i,s)),c.ye=h(c.ye,(e,t,n)=>{let r=tr(e);void 0!==r&&(r.D.ye(t,n),r.Rt.ye(t))}),c.Yt=h(c.Yt,(e,t,n)=>tr(e)?.D.Yt(t,n)),c.Te=h(c.Te,e=>{let t=tr(e);void 0!==t&&(t.D.Te(),t.Rt.Te())}),c.zt=d(p,c.zt,(e,t)=>{let n=t.split(".",1)[0];if(ir.includes(n))return n===t?e.target[t]:e.read(e.o(t),null)}),c.Pe=d(f,c.Pe,(e,t)=>(!Qn&&36===t.t.charCodeAt(0)&&ir.includes(t.t.split(".",1)[0])&&v(`"${t.t}" is read-only (the stream runtime owns it).`),!1))}},or=new WeakMap,lr=!1,ar=/^(?!prototype$)[^\d.*$][^.*]*$/;function ur(e,t){let n=t.$listKeys,r=new Map;if(void 0!==n){(null===n||"object"!=typeof n)&&v("$listKeys must be an object mapping list paths to a key field or function.");for(let t of Object.keys(n)){let i=n[t];"string"==typeof i?r.set(e.o(t),e=>e[i]):"function"==typeof i?r.set(e.o(t),i):v(`$listKeys "${t}" must be a field name or a function.`)}}or.set(t,r)}function cr(e){if(null===e||"object"!=typeof e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function hr(e,t,n){let r=new Map;for(let i of t){cr(i)||v(`$listKeys "${e}": rows must be plain objects.`);let t=n(i);null==t&&v(`$listKeys "${e}": a row has no key.`),r.has(t)&&v(`$listKeys "${e}": duplicate key ${JSON.stringify(t)}.`),r.set(t,i)}return r}function dr(e,t,n,r){if(lr||!Array.isArray(r))return!1;let i=or.get(e.target)?.get(t);if(void 0===i)return!1;let s=e.yt(t,n);if(!Array.isArray(s)||s===r)return!1;let o=hr(t.t,s,i);hr(t.t,r,i);let l=[],a=[],u=s.length===r.length;for(let e=0;e<r.length;e++){let t=r[e],n=o.get(i(t));l.push(n??t),void 0!==n&&a.push([e,n,t]),l[e]!==s[e]&&(u=!1)}let c=[];for(let[e,t,n]of a){for(let r of Object.keys(n))Object.is(t[r],n[r])||c.push([e,r,n[r]]);for(let r of Object.keys(t))!(r in n)&&null!==t[r]&&c.push([e,r,null])}if(u&&0===c.length)return!0;if(!u){lr=!0;try{e.P(t,n,l)}finally{lr=!1}}if(c.length>0){let r=e.De(0===t.n?null:n,t);for(let[n,i,s]of c){if("__proto__"===i)continue;let o=r.u[n],l=ar.test(i)?e.o(`${t.t}.*.${i}`):null;null===l?.getter?e.P(l,o,s):(o.T[i]=s,e.P(e.o(`${t.t}.*`),o,o.T,!0))}}return!0}var fr={name:"list-keys",install(){c.se=h(c.se,ur),c.Pe=d(f,c.Pe,dr)}},pr=new WeakMap,mr=new WeakMap,gr="will not graft: the root state failed to initialize.",yr=new WeakSet,br=new WeakMap,vr=["$stream","$streams","$scan","$recursion","$watch","$listKeys","$renderedCallback","$updatedCallback","$behavior","$features"],wr=["$commandTokens","$eventTokens","$on","$errorCallback"],_r=e=>`[@wcstack/state] <${re.tagNames.state} mount="${e}">`,$r=new Set(["$getAll","$setAll","$resolve","$postUpdate","$dependOn","$eq","$eqIndex"]),kr=e=>e?.element?.isConnected?e:void 0;function Sr(e){let t=mr.get(e);return void 0!==t&&!Array.isArray(t)&&t.isConnected}function Nr(e,t){let n=mr.get(t);if(mr.delete(t),Array.isArray(n))for(let t of n)xr(t,e)}function Ar(e){let t=pr.get(e.root);t?.get(e.t)===e&&t.delete(e.t)}function Er(e,t){console.error(`${_r(e.t)} ${t}`),Ar(e),e.Ge?.(),e.Ge=null}function Cr(e,t){let n=e.state?.[t];if("function"==typeof n)try{let t=n.call(e.chroot);null!==t&&"object"==typeof t&&"function"==typeof t.then&&t.then(void 0,e=>console.error(e))}catch(e){console.error(e)}}function xr(e,t){if(yr.has(t))return Er(e,"will not graft: its component is wired to its host.");let n=e.state,r=t.target,i=e.t.split("."),s=r;for(let e of i)s=s?.[e];if(void 0!==s&&!0!==t.hydrated)return Er(e,`will not graft: the root state already has "${e.t}".`);let o=function(e,t){let n=e=>`${t}.${e}`;return new Proxy({},{get(t,r){if("symbol"==typeof r)return;if(36!==r.charCodeAt(0))return e.proxy[n(r)];let i=e.proxy[r];return"$eqPath"===r?(e,t)=>i(n(e),n(t)):$r.has(r)&&"function"==typeof i?(e,...t)=>i(n(e),...t):i},set:(t,r,i)=>"symbol"!=typeof r&&(e.proxy[n(r)]=i,!0)})}(t,e.t);e.chroot=o;let l={},a={},u=new Set;for(let t=n;null!==t&&t!==Object.prototype;t=Object.getPrototypeOf(t))for(let n of Object.getOwnPropertyNames(t)){if(u.has(n)||"constructor"===n)continue;u.add(n);let{get:r,set:i,value:s}=Object.getOwnPropertyDescriptor(t,n);if(void 0!==r||void 0!==i)a[`${e.t}.${n}`]={get:r&&function(){return r.call(o)},set:i&&function(e){i.call(o,e)}};else{if("$"===n[0])continue;if("function"==typeof s){let t=s.bind(o);a[`${e.t}.${n}`]={get:()=>t}}else l[n]=s}}if(void 0===s){for(let e=1;e<i.length;e++){let n=t.o(i.slice(0,e).join("."));null==t.yt(n,null)&&t.P(n,null,{})}t.P(t.o(e.t),null,l)}t.Yn(Object.defineProperties({},a));for(let e in a)t.We(t.o(e),null);e.engine=t;let c=br.get(t);void 0===c&&br.set(t,c=[]),c.push(e),e.el.isConnected&&Cr(e,"$connectedCallback"),e.Ge?.(),e.Ge=null}function Tr(e,t){let n=mr.get(e);if(Array.isArray(n))for(let e of n)Er(e,gr);mr.set(e,t)}var Pr=new WeakMap;function Or(e,t){let n=e.getAttribute("mount");if(null===n)return null;let r={el:e,root:t,t:n,state:null,engine:null,chroot:null,Ge:null},i=null;if(function(e){return""!==e&&e.split(".").every(e=>""!==e&&!/[*$#@\s]/.test(e))}(n))if(e.hasAttribute(re.bindAttributeName))i='injections (data-wcs="state.<key>: …") are not supported — read the root path in a root getter.';else{let e=pr.get(t);void 0===e&&pr.set(t,e=new Map);let s=e.get(n);if(void 0!==s&&s!==r&&(null===s.engine?s.el.isConnected:kr(s.engine)))i=`will not graft: another volume already holds "${n}".`;else{if(null===s?.engine){let e=mr.get(t);Array.isArray(e)&&mr.set(t,e.filter(e=>e!==s)),s.Ge?.(),s.Ge=null}e.set(n,r)}}else i='has an invalid mount path: it must be a static path (no "*", "$", "#", "@").';return{vo:!0,start(e){if(null!==i)return Er(r,i);if(pr.get(t).get(n)===r){for(let t of vr)if(void 0!==e[t])return Er(r,`${t} is not run in a volume — declare it on the root state.`);for(let t of wr)void 0!==e[t]&&console.warn(`${_r(n)} ${t} is not run in a volume (it belongs to the root).`);return r.state=e,new Promise(e=>{r.Ge=e;let n=kr(It.get(t)),i=mr.get(t);void 0!==n?xr(r,n):Sr(t)?Er(r,gr):mr.set(t,[...Array.isArray(i)?i:[],r])})}},Xe(){null!==r.engine&&Cr(r,"$connectedCallback")},On(){null!==r.engine&&Cr(r,"$disconnectedCallback")},reset(){v(`re-setting a volume is not supported: its data was copied into the root tree at "${n}" — write the paths under it on the root instead.`)}}}var Mr=new WeakMap,Lr=new WeakMap;function Ir(e,t){let n=e[t];if(void 0===n)return[];Array.isArray(n)||v(`${t} must be an array of state member names.`);let r=new Set;for(let e of n)("string"!=typeof e||""===e)&&v(`${t} entries must be non-empty strings.`),"$"===e[0]&&v(`${t} entry "${e}": internal ($) members are never exposed.`),r.has(e)&&v(`${t} entry "${e}" is duplicated.`),r.add(e);return n}function jr(e,t){let n=t.host;if(void 0===n||!n.hasAttribute("data-wc-definition"))return null;let r=document.createDocumentFragment();for(let e of[...t.childNodes])r.appendChild(e.cloneNode(!0));let i=t.mode;return{start(t){e.hasAttribute("bind-component")&&v("DCC: a <wcs-state bind-component> cannot define a component (use one mechanism)."),function(e,t,n,r){e.includes("-")||v(`DCC: <${e} data-wc-definition> is not a valid custom element name.`),void 0!==customElements.get(e)&&v(`DCC: <${e}> is already defined.`);let i=function(e){let t=new Map;for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n))for(let e of Object.getOwnPropertyNames(n))"constructor"===e||"$"===e[0]||t.has(e)||t.set(e,Object.getOwnPropertyDescriptor(n,e));let n=e.$stream;if(null!==n&&"object"==typeof n)for(let e of Object.keys(n))t.has(e)||t.set(e,{value:void 0});return t}(r),s=Ir(r,"$bindables"),o=Ir(r,"$commands");for(let e of s){let t=i.get(e);void 0===t&&v(`$bindables entry "${e}" does not exist on the state.`),"function"==typeof t.value&&v(`$bindables entry "${e}" is a method: list it in $commands.`)}for(let e of o){let t=i.get(e);void 0===t&&v(`$commands entry "${e}" does not exist on the state.`),"function"!=typeof t.value&&v(`$commands entry "${e}" is not a method: list it in $bindables.`)}let l={tag:e,bindables:s},a=new WeakMap,u=new WeakMap,c=r=>{if(a.has(r))return a.get(r);if(r.hasAttribute("data-wc-definition"))return null;let i=r.attachShadow({mode:n});i.appendChild(t.cloneNode(!0));let o=i.querySelector(re.tagNames.state);return a.set(r,o),Mr.set(r,l),null===o&&s.length>0&&console.warn(`[@wcstack/state] DCC: <${e}> declares $bindables but its content has no <${re.tagNames.state}>: no change events.`),o},h=e=>c(e)?.engine??null,d=e=>Promise.resolve(c(e)?.initializePromise).then(()=>{let t=u.get(e);u.delete(e);let n=h(e);if(void 0!==t&&null!==n)for(let[e,r]of t)n.proxy[e]=r});class f extends HTMLElement{static{this.wcBindable=0===s.length&&0===o.length?null:{protocol:"wc-bindable",version:1,properties:s.map(t=>({name:t,event:`${e}:${t}-changed`,getter:e=>e.target[t]})),inputs:s.map(e=>({name:e})),...0===o.length?{}:{commands:o.map(e=>({name:e,async:!0}))}}}connectedCallback(){null!==c(this)&&d(this)}get stateElement(){return c(this)}}for(let[e,t]of i)"function"==typeof t.value?Object.defineProperty(f.prototype,e,{configurable:!0,value(...t){return d(this).then(()=>{let n=h(this);return null===n?void 0:n.proxy[e].apply(n.proxy,t)})}}):Object.defineProperty(f.prototype,e,{configurable:!0,get(){return h(this)?.proxy[e]},set(t){let n=h(this);if(null!==n)n.proxy[e]=t;else{let n=u.get(this);void 0===n&&u.set(this,n=[]),n.push([e,t])}}});customElements.define(e,f)}(n.localName,r,i,t)},Xe(){},On(){},reset(){v("re-setting a DCC definition is not supported: each instance loads its own state.")}}}var Rr=new WeakMap,Hr=new WeakSet,Wr=new WeakMap,zr=new WeakMap,Dr="data-wcs-wired",Ur=new WeakMap,Fr=new WeakMap,qr=new WeakMap,Br=0,Kr=new Set,Gr={},Vr=["$watch","$stream","$renderedCallback"],Jr=e=>e.split(".",1)[0];function Qr(e,t){let n=0;return e.split(".").map(e=>"*"===e?String(t[n++]):e).join(".")}function Xr(e,t){let n=e.a,r=Jr(e.name);if(!0!==document.documentElement?.hasAttribute("data-wcs-server"))n.removeAttribute(Dr);else if(!Zr(n,r)){let e=n.getAttribute(Dr)?.split(" ")??[];e.includes(r)||n.setAttribute(Dr,[...e,r].join(" "))}Ur.get(n)?.ce===r&&v(`<${n.localName}>.${r} has loaded its state: the wiring "${e.name}" added afterwards cannot reach it — bind the host's wiring before the component loads.`);let i=Rr.get(n);void 0===i&&Rr.set(n,i=[]),i.push(e),t&&Hr.add(e);let s=Wr.get(n);return void 0===s&&Wr.set(n,s=new Map),s.has(r)||s.set(r,n[r]),zr.get(n)?.(),!1}function Yr(e){return e.localName.includes("-")&&null!==e.querySelector(`:scope > ${re.tagNames.state}[bind-component]`)}function Zr(e,t){let n=e.getAttribute(re.bindAttributeName);return null!==n&&new RegExp(`(^|;)\\s*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[.#:]`).test(n)}function ei(e){let t=e.parentElement;for(;null!==t&&!Yr(t);)t=t.parentElement;let n=It.get(t??e.getRootNode()),r=n?.element;(r?.isConnected?r.W:null===t)&&(null===t?Ft(e):Rt(n,e))}var ti=new Set;function ni(e,t){ti.has(e)||(ti.add(e),console.warn(`[@wcstack/state] ${t}`))}var ri=(e,t)=>t in e.state;function ii(e,t){let n=si(e.state,t);return void 0!==n&&(void 0!==n.get||void 0!==n.set||"function"==typeof n.value)}function si(e,t){for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e}}function oi(e,t,n){if(null!==n.getter)return;let r,i=e.host,s=i.engine,o=Jr(n.t),l=i.entries.find(e=>e.E===n.t);if(void 0===l&&null!==n.d)return function(e,t){let n,r=t.d;for(;null!==r&&void 0===(n=e.at.get(r));)r=r.d;if(null===r||void 0===n)return;let i=e.x,s=e.host.engine,o=s.o(n.p.t+t.t.slice(r.t.length));if(null===o.getter)return;let l=n,a=()=>{let n=li(e,l.r);return 0===t.n?n:(s.resolve(Qr(o.t,[...s._(n),...i._(ee(i.c,t.n))]),null),s.rr)};t.getter=()=>{let e=a();return o.n>0&&null===e?void 0:s.v(o,e)},null!==o.oe&&(t.oe=n=>{let r=a();ai(e,l.e,()=>s.P(o,r,n)),e.cn=t}),t.n>0&&(t.F=i.Oe++),e.at.set(t,{e:l.e,p:o,r:l.r})}(e,n);if(0!==n.n)return;if(void 0!==l){if(l.E!==o?ri(i,o):ii(i,o))return;r=l.ue}else{if(null===t||null!==n.d||"$"===o[0]||ri(i,o))return;l=t,r=s.o(`${t.ue.t}.${o}`)}let a=l.r,u=l;n.getter=()=>s.v(r,li(e,a)),n.oe=t=>{ai(e,u,()=>s.P(r,a,t)),e.cn=n},e.at.set(n,{e:l,p:r,r:a})}function li(e,t){return null!==t&&!t.y&&v(`The host row of <${e.host.el.localName}> was removed.`),t}function ai(e,t,n){let r=Kr.has(e.x);Kr.add(e.x),e.from=t;try{n()}finally{r||Kr.delete(e.x),e.from=null}}var ui=(e,t)=>t||!Kr.has(e.m.x)||null!==e.m.from&&e.m.from!==e.e;function ci(e,t){if(e.un===t||null===e.host.engine)return;e.un=t,Br+=t?1:-1;let n=e.host.engine,r=qr.get(n);void 0===r&&qr.set(n,r=new Map);for(let n of e.ae){let e=r.get(n.e.ue);void 0===e&&r.set(n.e.ue,e=new Map);let i=e.get(n.e.r);void 0===i&&e.set(n.e.r,i=new Set),t?i.add(n):(i.delete(n),0===i.size&&e.delete(n.e.r))}let i=e.host.entries.find(e=>""===e.E);if(void 0!==i){null===e.te&&function(e,t){let n=e.host,r=n.engine;e.te=new Map;let i=new Set;for(let s=n.state;null!==s&&s!==Object.prototype;s=Object.getPrototypeOf(s))for(let o of Object.getOwnPropertyNames(s)){if(i.has(o))continue;i.add(o);let l=Object.getOwnPropertyDescriptor(s,o);if(void 0===l.get&&void 0===l.set||"$"===o[0]||o.includes("*"))continue;let a=Jr(o);if(o!==a&&!ri(n,a))continue;let u=r.o(`${t.ue.t}.${o}`);if(null===u.getter)fi(r,u,t.ue);else if(!hi.has(u.getter))continue;e.te.set(u,e.x.o(o))}}(e,i);for(let r of e.te.keys())t&&null===r.getter&&fi(n,r,i.ue),n.R.me(n,r,i.r);e.te.size>0&&n.Re(),t&&function(e,t){let n=e.host.engine;for(let[r,i]of e.te){let s=n.v(r.d,t.r);if(null===s||"object"!=typeof s||!(r.s in s))continue;let o=e.host.el.localName;ni(`${o}|${r.t}`,`[wcs/mount-export-shadowed] <${o}>.${e.host.ce}.${i.t} is exported at "${r.t}" 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,i)}}var hi=new WeakSet;function di(e,t,n,r){let i=qr.get(e)?.get(t)?.get(n);if(void 0===i)return null;let s=null;for(let e of i)""!==e.e.E||!0!==e.m.te?.has(r)||e.m===s||(null!==s&&v(`[wcs/mount-export-ambiguous] "${r.t}" is exported by two mounted components on the same instance: <${s.host.el.localName}> and <${e.m.host.el.localName}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),s=e.m);return s}function fi(e,t,n){let r=t.d,i=t.s,s=()=>{let t=e.read(r,e.c);return null!==t&&"object"==typeof t&&i in t?t:null};t.getter=()=>{let r=s();if(null!==r)return r[i];let o=di(e,n,e.c,t);return null===o?void 0:o.x.read(o.te.get(t),null)},hi.add(t.getter),t.oe=o=>{let l=null===s()?di(e,n,e.c,t):null;if(null===l){let t=e.read(r,e.c);return void(null!==t&&"object"==typeof t&&(t[i]=o))}let a=l.te.get(t);void 0===si(l.host.state,a.t)?.set&&v(`Cannot write to "${a.t}" on mounted <${l.host.el.localName}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),l.x.P(a,null,o)},t.n>0&&(t.F=e.Oe++)}function pi(e,t,n,r,i,s){if(null!==t.getter)return e.R.me(e,t,n),void e.Re();if("*"===t.s){if(null===n)return;if(n.T=n.l.C[n.b],e.R.qt(n),null!==n.h)for(let t of n.h.values())e.z(t)}else e.wn(t,n);c.he?.(e,t,n,r,i,s),e.We(t,n)}function mi(e){let t=e.m.x;for(let[n,r]of e.m.at)r.e===e.e&&(0===n.n?t.R.me(t,n,null):t.Zt(n.f[n.n],e=>t.R.me(t,n,e)));t.Re()}function gi(e,t,n,r,i,s,o){let l=n.t.slice(t.t.length);if(""===l)return mi(e);let a,u=e.m,c=u.x;if(""===e.e.E){a=l.slice(1);let e=Jr(a);if("$"===e[0]||ri(u.host,e)||u.host.entries.some(e=>""!==e.E&&(a===e.E||a.startsWith(`${e.E}.`))))return}else a=e.e.E+l;let h=[];for(let e=t.n+1;e<=n.n;e++)h.push(ee(r,e).b);c.resolve(Qr(a,h),null);let d=c.rp,f=c.rr;d.n>0&&null===f||pi(c,d,f,i,s,o)}function yi(e,t,n,r,i,s,o){if(0===Br)return;let l=Kr.has(e);Kr.add(e);try{let l=Fr.get(e);!o&&void 0!==l&&l.un&&!Kr.has(l.host.engine)&&function(e,t,n,r,i,s){let o,l=t;for(;null!==l&&void 0===(o=e.at.get(l));)l=l.d;if(null===l||void 0===o)return;let a=e.host.engine;if(l===t&&e.cn===t)return void(e.cn=null);if(null!==o.r&&!o.r.y)return;let u=[...a._(o.r),...e.x._(n)];a.resolve(Qr(o.p.t+t.t.slice(l.t.length),u),null);let c=a.rp,h=a.rr;c.n>0&&null===h||ai(e,o.e,()=>pi(a,c,h,r,i,s))}(l,t,n,r,i,s),o&&void 0!==l&&l.un&&null!==l.te&&function(e,t){let n=e.host.entries.find(e=>""===e.E),r=e.host.engine;for(let[i,s]of e.te)s===t&&(r.R.me(r,i,n.r),r.Re())}(l,t);let a=qr.get(e);if(void 0===a)return;for(let[e,l]of a)if(t.Q(e)){let a=l.get(0===e.n?null:ee(n,e.n));if(void 0!==a)for(let l of[...a])ui(l,o)&&gi(l,e,t,n,r,i,s)}else if(e.Q(t))for(let[e,r]of[...l])if(0===t.n||ee(e,t.n)===n)for(let e of[...r])ui(e,o)&&mi(e)}finally{l||Kr.delete(e)}}async function bi(e,t,n,r,i){if(r===Gr)return;let s=y(r);s&&await s;let o=Ur.get(t);o.engine&&r.$recursion&&v(`[wcs/mount-dollar-declaration] <${t.localName}>: $recursion is not run in a mounted component — declare it on the root state.`);let l=o.O;if(null!==l&&l.el!==e&&l.el.isConnected&&v(`<${t.localName}> already has a connected <${re.tagNames.state} bind-component="${o.ce}">.`),null!==l&&ci(l,!1),null!==l&&function(e,t,n){let r=e.x,i=`[${re.bindAttributeName}]`,s=e=>1===e.nodeType&&(e.matches(i)||null!==e.querySelector(i)),o=new Set,l=e=>{for(;null!==e&&e.parentNode!==n;)e=e.parentNode;null!==e&&o.add(e)},a=(e,t)=>{for(let n=e.Pn(t);null!==n&&n!==t;n=n.nextSibling)l(n);l(t)};for(let e of r.ie.values())for(let t of e)if(null===t.M)l(t.a);else for(let e of t.M.X)a(t.M,e.S);for(let e of r.ee.values())for(let t of[e.$,...e.L??[]])null!==t&&a(t,t.S);for(let t of e.j)t.parentNode===n&&s(t)&&o.add(t);if(0===o.size)return!1;let u=[...n.childNodes].filter(n=>n!==t&&!o.has(n)&&!e.j.includes(n)&&(s(n)||r.Lt&&n.textContent.includes("{{")));return u.length>0&&console.warn(`[@wcstack/state] <${e.host.el.localName}>: ${u.length} node(s) added beside the content taken over are not bound.`),!0}(l,e,n))return async function(e,t,n,r){e.el.engine=null,e.el=t,e.x.element=t,t.engine=e.x,e.j=e.j.filter(e=>e.parentNode===n),t.isConnected?await vi(e,r):r()}(l,e,n,i);let a=new ne(r,new Bt);a.element=e,e.engine=a,function(e,t){let n=new Map;for(let e=t;null!==e&&e!==Object.prototype;e=Object.getPrototypeOf(e))for(let t of Object.getOwnPropertyNames(e)){let r=Object.getOwnPropertyDescriptor(e,t).value;"function"==typeof r&&"constructor"!==t&&n.set(r,null)}let r=(t,n,r)=>Reflect.apply(t,e.proxy,r);e.W=e=>{let t=n.get(e);return null===t&&n.set(e,t=new Proxy(e,{apply:r})),t}}(a,r);let u={el:e,j:[],x:a,host:o,ae:[],at:new Map,un:!1,cn:null,from:null,te:null};for(let e of o.entries)u.ae.push({m:u,e:e});o.O=u,Fr.set(a,u);let h=null===o.engine;h?c.element?.(a,"mounting"):(function(e){let t=e.x,n=e.host,r=n.engine,i=n.el.localName,s=n.entries.find(e=>""===e.E)??null;for(let e of n.entries){if(""===e.E)continue;let t=Jr(e.E);ri(n,t)&&(e.E!==t||ii(n,t))&&ni(`${i}.${e.E}`,`[wcs/mount-own-key-shadow] <${i}>: "${n.ce}.${e.E}" is hidden by the component's own "${t}"; rename one side.`)}if(null!==s){let e=r.v(s.ue,s.r);if(null!==e&&"object"==typeof e)for(let t of Object.keys(n.state))"$"!==t[0]&&t in e&&!n.entries.some(e=>e.E===t)&&ni(`${i}.${t}`,`[wcs/mount-own-key-shadow] <${i}>: its own "${t}" hides "${s.ue.t}.${t}" — remove the default to read the tree, or rename it to keep it private.`)}let o=Vr.filter(e=>void 0!==n.state[e]);o.length>0&&ni(`${i}.${n.ce}$`,`[wcs/mount-dollar-declaration] <${i}>: ${o.join(", ")} ${1===o.length?"is":"are"} not run in a mounted component — declare it on the root state.`);let l=t.et;t.et=n=>{oi(e,s,n),l.call(t,n)};let a=[...t.B.all()];for(let t of a)oi(e,s,t);for(let e of a)l.call(t,e);let u=n.entries.filter(e=>null!==e.r);if(u.length>0){let e=t.Ut;t.Ut=()=>{u.every(e=>e.r.y)&&e.call(t)}}}(u),ci(u,!0),yr.add(a),Nr(a,n));let d=c.ir?.(n);jt(a,n),d?.(),u.j=[...n.childNodes],qt(),h&&a.bn(),Object.defineProperty(t,o.ce,{configurable:!0,enumerable:!0,get:()=>a.proxy});let f=t.$stateReadyCallback;if("function"==typeof f)try{let e=f.call(t,o.ce);null!==e&&"object"==typeof e&&"function"==typeof e.then&&e.then(void 0,e=>console.error(e))}catch(e){console.error(e)}i(),e.isConnected?(await a.we("$connectedCallback"),h&&e.isConnected&&c.element?.(a,"connected")):ci(u,!1)}async function vi(e,t){ci(e,!0);for(let t of e.ae)mi(t);t?.(),!e.broken&&(await e.x.we("$connectedCallback"),null===e.host.engine&&e.el.isConnected&&c.element?.(e.x,"connected"))}function wi(e,t){let n=e.getAttribute("bind-component");if(null===n)return function(e,t){return e.connectedCallbackPromise.catch(()=>{let n=It.get(t)?.element;if(!(e.W||void 0!==n&&n!==e&&n.isConnected)){Tr(t,e);for(let e of Pr.get(t)??[])e()}}),null}(e,t);let r=e.parentNode,i=r instanceof ShadowRoot,s=i?r.host:r instanceof Element?r:null,o=()=>{let t=null===s?void 0:Ur.get(s)?.O;return t?.el===e?t:null},l=t=>{throw i&&Tr(r,e),t},a=!1;return{jt:()=>(null!==s&&s.localName.includes("-")?async function(e,t,n,r){let i=n.localName;(["state","src","json"].some(t=>e.hasAttribute(t))||null!==e.querySelector('script[type="module"]'))&&v(`<${re.tagNames.state} bind-component> takes its state from <${i}>.${t}: it cannot also load one (state / src / json / an inline script).`),await Ie(n).whenDefined(i);let s=Ur.get(n);if(void 0!==s)return s.ce!==t&&v(`<${i}> already has a <${re.tagNames.state} bind-component="${s.ce}">.`),s.state;let o=()=>(Rr.get(n)??[]).filter(e=>Jr(e.name)===t),l=Zr(n,t);if(l&&0===o().length&&ei(n),0===o().length&&(l||((e,t)=>!0===e.getAttribute(Dr)?.split(" ").includes(t))(n,t))){let e;await new Promise((r,s)=>{zr.set(n,r),e=function(e,t){Sr(e)&&t();let n=Pr.get(e)??new Set;return Pr.set(e,n.add(t)),()=>n.delete(t)}(n.getRootNode(),()=>s(new Error(`[@wcstack/state] <${i}>.${t} will not mount: the root state failed to initialize.`)))}).finally(()=>e())}zr.delete(n);let a=o(),u=Wr.get(n),c=void 0!==u&&u.has(t)?u.get(t):n[t];if((null===c||"object"!=typeof c)&&v(`"bind-component": <${i}>.${t} must be an object (the component's state), got ${null===c?"null":typeof c}.`),0===a.length&&r){let e=new Error(`[@wcstack/state] A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${i}>, or mount it from the host (${re.bindAttributeName}="${t}: path").`);return queueMicrotask(()=>{throw e}),Gr}let h=[];for(let e of a){let r=e.name===t?"":e.name.slice(t.length+1);h.some(e=>e.E===r)&&v(`<${i}> maps "${e.name}" twice.`);let s=r.split(".").indexOf("*");if(s>=0){let n=r.split(".").slice(0,s).join(".");v(`<${i}> maps "${e.name}": the component-side path of a mount cannot contain "*"${""===n?"":` — map the list itself ("${t}.${n}: <the host's list>")`}.`)}h.push({E:r,ue:e.o,r:e.r,ro:Hr.has(e)}),e.engine.kn(e),""!==r&&delete n[e.name]}let d=0===a.length?function(e){let t=Object.getOwnPropertyDescriptors(e),n=Object.isFrozen(e);for(let e of Object.values(t))"value"in e&&!1===e.writable&&(e.writable=!0,n=!0);return n?Object.create(Object.getPrototypeOf(e),t):e}(c):c;return Ur.set(n,s={el:n,ce:t,state:d,engine:0===a.length?null:a[0].engine,entries:h,O:null}),d}(e,n,s,!i):Promise.reject(new Error(`[@wcstack/state] "bind-component" requires <${re.tagNames.state}> to be a direct child of a custom element.`))).catch(l),async start(t,n){await bi(e,s,i?r:s,t,()=>{a=!0,n()}).catch(e=>{let t=o();return!a&&null!==t&&(t.broken=!0),l(e)})},Xe(){let t=o();null!==t?vi(t).catch(e=>console.error(e)):a?Promise.resolve().then(()=>{if(e.parentNode===r)return bi(e,s,i?r:s,Ur.get(s).state,()=>{})}).catch(e=>console.error(e)):zr.has(s)&&ei(s)},On(){let e=o();null!==e&&(ci(e,!1),!e.broken&&(e.x.we("$disconnectedCallback"),null===e.host.engine&&c.element?.(e.x,"disconnected")))},reset(){v(`re-setting a component's state is not supported: write <${s?.localName}>.${n} instead.`)}}}var _i={name:"scopes",install(){c.rt=d(m,c.rt,Or),c.rt=d(m,c.rt,jr),c.rt=d(m,c.rt,wi),c.Jo=Xr,c.yo=Yr,c.element=h(c.element,(e,t)=>{if("mounting"!==t)return function(e,t){let n=br.get(e)??[];if("disconnected"===t)for(let e of n)Ar(e);else if("reset"!==t&&kr(It.get(e.root))===e){Nr(e,e.root);for(let e of n)pr.get(e.root).has(e.t)||pr.get(e.root).set(e.t,e)}}(e,t);let n=e.element.getRootNode();Nr(e,n),function(e,t){let n=t.host,r=void 0===n?void 0:Mr.get(n);void 0!==r&&Lr.set(e,{host:n,def:r})}(e,n)}),c.he=h(c.he,(e,t,n,r,i,s)=>{(function(e,t,n,r){let i=Lr.get(e);if(void 0===i)return;let s=t.t.split(".",1)[0];if(!i.def.bindables.includes(s))return;let o=r&&t.t===s;i.host.dispatchEvent(new CustomEvent(`${i.def.tag}:${s}-changed`,{detail:o?n:void 0,bubbles:!0}))})(e,t,i,s),yi(e,t,n,r,i,s,!1)}),c.ye=h(c.ye,(e,t,n)=>yi(e,t,n,void 0,void 0,!1,!0)),c.Pe=d(f,c.Pe,(e,t,n,r,i)=>(function(e,t){let n=br.get(e);if(void 0!==n&&0===t.n)for(let{t:e}of n)e.startsWith(`${t.t}.`)&&v(`writing "${t.t}" would replace the volume grafted at "${e}"; write the paths under it instead.`)}(e,t),function(e,t,n){let r,i=Fr.get(e);if(void 0===i)return!1;for(let e=t;null!==e&&void 0===r;e=e.d)r=i.at.get(e);if(void 0===r)return!1;let s=r.e;return!((null===s.r||s.r.y)&&!s.ro)&&(!!n||(li(i,s.r),void v(`[wcs/mount-readonly] <${i.host.el.localName}> cannot write "${t.t}": it is mounted read-only ("${i.host.ce}${""===s.E?"":`.${s.E}`}#ro: ${s.ue.t}"). Write it on the host, or drop #ro from the mount.`)))}(e,t,i)));let e=c.se;c.se=(t,n)=>{let r=br.get(t);void 0!==r&&r.length>0&&v(`re-setting a root state with grafted volumes (${r.map(e=>e.t).join(", ")}) is not supported: their data is part of the tree.`),function(e){let t=qr.get(e);if(void 0===t)return!1;for(let e of t.values())if(e.size>0)return!0;return!1}(t)&&v("re-setting a root state with mounted components is not supported: they read its data."),e?.(t,n)}}},$i="$recursion",ki=new WeakMap,Si=new WeakSet,Ni=new WeakSet,Ai=0,Ei=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ci=e=>`[wcs/recursion-${e}]`;function xi(e,t){let n=n=>v(`${Ci("declaration-invalid")} ${$i} ${e} "${String(t)}" ${n}`);("string"!=typeof t||""===t)&&v(`${Ci("declaration-invalid")} ${$i} ${e} must be a non-empty string.`);let r=t.split(".");(r.length<2||"*"!==r[r.length-1])&&n('must end with ".*" (a list element).');for(let e=0;e<r.length-1;e++){let t=r[e];""===t&&n("must not contain empty path segments."),("*"===t||"**"===t||/^\d/.test(t))&&n('must have exactly one "*", at the end.'),t.includes("#")&&n('must not contain "#".')}return"$"===t[0]&&n('must not start with "$".'),t}var Ti=(e,t)=>`${e.l}.*${e.step.repeat(t)}`;function Pi(e,t){let n=`${e.l}.**`,r=t.slice(n.length);return(!t.startsWith(n)||""!==r&&"."!==r[0]||r.includes("**"))&&v(`[wcs/recursion-anchor] "${t}" does not start at the recursion anchor "${e.l}.*".`),r}function Oi(e,t,n){let r=Pi(e,t),i=function(e,t){for(let n=t;null!==n;n=n.l.re){let t=e.nodeList.exec(n.l.o.t);if(null!==t)return{k:t[1].length/(e.key.length+3),r:n}}return null}(e,n);return null===i&&v(`[wcs/recursion-context] "${t}" uses "**", which is bound to the depth of the row it is evaluated in; there is none here — use $getAll("${t}", []) for every depth.`),Ti(e,i.k)+r}function Mi(e,t,n){let r=new Set,i=new Set,s=(e,n,s)=>!(!Array.isArray(e)||0===e.length||(r.has(e)&&v(`${Ci("cycle")} "${n}" is reachable from itself: the data under "${t.l}" must be a tree.`),i.has(e)&&v(`${Ci("shared-list")} "${n}" is the same array instance as a list reached before: the data under "${t.l}" must be a tree.`),s+1>128&&v(`${Ci("depth-exceeded")} Recursion on "${t.l}.*" reached depth ${s+1} (the limit is 128).`),i.add(e),0)),o=(i,l)=>{for(let a of i){n(l,a);let i=e.o(`${Ti(t,l)}.${t.key}`),u=e.read(i,a);s(u,i.t,l+1)&&(r.add(u),o(e.De(a,i).u,l+1),r.delete(u))}},l=e.o(t.l),a=e.read(l,null);s(a,t.l,0)&&(r.add(a),o(e.De(null,l).u,0))}function Li(e,t){let n=function(e){let t=e[$i],n=[],r=new Set;for(let t=e;null!==t&&t!==Object.prototype;t=Object.getPrototypeOf(t))for(let e of Object.getOwnPropertyNames(t))!r.has(e)&&e.includes("**")&&n.push([e,Object.getOwnPropertyDescriptor(t,e)]),r.add(e);if(void 0===t)return n.length>0&&z(n[0][0]),null;(null===t||"object"!=typeof t||Array.isArray(t))&&v(`${Ci("declaration-invalid")} ${$i} must be an object mapping one anchor path to its repeating sub-path.`);let i=Object.entries(t);1!==i.length&&v(`${Ci("declaration-invalid")} ${$i} must declare exactly one anchor (it declares ${i.length}).`);let s=xi("anchor",i[0][0]),o=xi("repeat",i[0][1]),l=s.slice(0,-2),a=o.slice(0,-2),u=`.${o}`,c=new Map,h=[],d=`${l}.**`;for(let[e,t]of n){let n=e.slice(d.length);(!e.startsWith(d)||""!==n&&"."!==n[0]||n.includes("**"))&&v(`[wcs/recursion-anchor] "${e}": a recursive key is "${d}" followed by a path (the anchor is "${s}").`),(""===n||n.split(".").slice(1).some(e=>""===e))&&v(`[wcs/recursion-anchor] "${e}" needs a path after "**".`),(void 0===t.get||void 0!==t.set)&&v(`${Ci("declaration-invalid")} "${e}": a recursive key is a getter without a setter.`),c.set(n,t.get),h.push([new RegExp(`^${Ei(s)}((?:${Ei(u)})*)${Ei(n)}$`),n])}return{l:l,step:u,key:a,families:c,matchers:h,owners:new Map,nodeList:new RegExp(`^${Ei(l)}((?:${Ei(`.*.${a}`)})*)$`)}}(t),r=ki.has(e);null!==n?(r||Ai++,ki.set(e,n),Ni.add(e),Si.has(e)||function(e){Si.add(e);let t=e,n=t.et;t.et=r=>{let i=ki.get(e);if(r.t.includes("**")){let t=e.B.Ot(r.t)===r;return void(Ni.has(e)||void 0===i&&t?r.getter=()=>z(r.t):t||n.call(e,r))}if(void 0!==i&&null===r.getter)for(let[e,n]of i.matchers)if(e.test(r.t)){r.getter=i.families.get(n),r.n>0&&(r.F=t.Oe++),i.owners.set(r,i.l+".**"+n);break}n.call(e,r)};let r=t.resolve;t.resolve=(t,n)=>{let i=ki.get(e);return r.call(e,void 0!==i&&t.includes("**")?Oi(i,t,n):t,n)};let i=t.getAll;t.getAll=(n,r)=>{let s=ki.get(e);if(void 0===s||!n.includes("**"))return i.call(e,n,r);if(void 0===r)return i.call(e,Oi(s,n,t.c));(!Array.isArray(r)||r.length>0)&&v(`${Ci("getall-form")} $getAll("${n}", indexes) with "**" takes either no indexes (this depth) or [] (every depth).`);let o=Pi(s,n),l=[];return Mi(e,s,(t,n)=>{for(let r of i.call(e,Ti(s,t)+o,e._(n)))l.push(r)}),l};let s=t.pn;t.pn=(n,r,i,o)=>{let l=ki.get(e);if(void 0===l||!n.includes("**"))return s.call(e,n,r,i,o);Array.isArray(r)||k(9,[n]),r.length>0&&v(`${Ci("setall-form")} $setAll("${n}", indexes, …) with "**" takes no partial prefix: pass [] to write every node.`),("function"==typeof i||!0===o?.spread)&&v(`${Ci("setall-form")} $setAll("${n}", [], value) with "**" takes a plain value (no mapper, no spread).`),t.Ce>0&&k(8);let a=Pi(l,n),u=a.replace(/\.\d+(?=\.|$)/g,".*");for(;u.startsWith(l.step);)u=u.slice(l.step.length);let c=l.key.split(".");(""===u||u===`.${l.key}.length`||c.some((e,t)=>u===`.${c.slice(0,t+1).join(".")}`))&&v(`${Ci("structural-write")} "${n}" writes the recursion structure itself (a node, its "${l.key}" list or that list's length, or an object on the way to it).`);for(let e of l.families.keys()){let t=e;for(;t.startsWith(l.step);)t=t.slice(l.step.length);(u===t||u.startsWith(`${t}.`))&&v(`${Ci("readonly")} "${n}" writes into the recursive getter "${l.l}.**${e}".`)}let h=[];Mi(e,l,(e,t)=>h.push([e,t]));let d=0;for(let[t,n]of h)d+=s.call(e,Ti(l,t)+a,e._(n),i);return d}}(e)):r&&(ki.delete(e),Ai--)}function Ii(e,t){if(0===Ai)return!1;let n=ki.get(e);if(void 0===n)return!1;for(let e=t;null!==e;e=e.d){let r=n.owners.get(e);void 0!==r&&v(`${Ci("readonly")} "${t.t}" writes into the recursive getter "${r}".`)}return!1}var ji={name:"recursion",install(){c.se=h(c.se,Li),c.element=h(c.element,(e,t)=>{("mounting"===t||"reset"===t)&&function(e){Ni.delete(e)}(e)}),c.Pe=d(f,c.Pe,Ii)}},Ri="4.0.0-rc.3",Hi=e=>e.split(".").slice(0,2).join("."),Wi=class extends Qt{static find(e){return e.querySelector?.(re.tagNames.ssr)??null}get version(){return this.getAttribute("version")??""}get stateData(){let e=this.querySelector('script[type="application/json"]');return null===e?{}:JSON.parse(e.textContent||"{}")}get templates(){let e=new Map;for(let t of Array.from(this.children))"template"===t.localName&&e.set(t.id,t);return e}get hydrateProps(){return{}}getTemplate(e){return this.templates.get(e)??null}verifyVersion(){return Hi(this.version)===Hi(Ri)}};function zi(e){let t=re.tagNames.ssr;void 0===e.get(t)&&e.define(t,class extends Wi{})}var Di=()=>re.tagNames.ssr,Ui=Symbol.for("wcstack.ssr.snapshotBuilder"),Fi=()=>!0===document.documentElement?.hasAttribute("data-wcs-server"),qi=e=>document.createComment(e),Bi=(e,t)=>null!==e&&8===e.nodeType&&e.data===t,Ki=(e,t)=>null!==e&&8===e.nodeType&&e.data.startsWith(t),Gi=new WeakMap,Vi=new WeakMap,Ji=new WeakMap,Qi=new WeakSet,Xi=new WeakMap;function Yi(e,t){let n=[];for(let r=e;null!==r&&(n.push(r),r!==t);r=r.nextSibling);return n}function Zi(e,t,...n){for(let n of Array.from(e.attributes))t.setAttribute(n.name,n.value);return(t.content??t).append(...n),t}var es=e=>null===e.j?e.Ue:e.j[e.j.length-1];function ts(e,t,n){let r=[qi(null===n?"wcs-[":`wcs-[:${n}`)];for(let e of t)null===n&&r.push(qi("wcs-|")),r.push(...Yi(e.Ue,es(e)));r.push(qi("wcs-]")),e.after(...r);for(let e of r)Qi.add(e)}function ns(e){if(e instanceof lt){ts(e.S,e.Ee,null);for(let t of e.Ee)rs(t);return}let t=e.O;null!==t&&(ts(e.X[e.X.length-1].S,[t],e.b),rs(t))}function rs(e){if(null!==e.h)for(let t of e.h)ns(t)}var is=new Set(["script","style","template","textarea","title"]),ss="data-wcs-raw",os=e=>is.has(e.localName)||e.localName===Di();function ls(e){for(let t of Array.from(e.childNodes))3===t.nodeType?""===t.data?t.replaceWith(qi("wcs-e")):null!==t.nextSibling&&3===t.nextSibling.nodeType&&t.after(qi("wcs-s")):1===t.nodeType&&!os(t)&&ls(t)}var as=0;function us(e,t){let n=e.getRootNode(),r=[t];for(let e of Vi.get(n)??[])e!==t&&!0===e.element?.hasAttribute("bind-component")&&r.push(e);let i=new Map;for(let e of r){let t=Gi.get(e);if(void 0===t)continue;let n=new Map;for(let t of e.ee.values())if(null!==t.$&&n.set(t.$.S,t.$),null!==t.L)for(let e of t.L)n.set(e.S,e);for(let t of e.ie.values())for(let e of t)if(null!==e.M)for(let t of e.M.X)n.set(t.S,e.M);let r=new Set;for(let[e,s]of t){i.set(e,s);let t=n.get(e);void 0!==t&&!r.has(t)&&e.isConnected&&(r.add(t),ns(t))}}for(let e of Array.from(n.querySelectorAll("*"))){let t=Ji.get(e);if(void 0!==t){let n=document.createTreeWalker(e,133,{acceptNode:e=>Qi.has(e)||1===e.nodeType&&t.has(e)&&ps(e)?2:1}),r=[];for(let e=n.nextNode();null!==e;e=n.nextNode()){let n=e.previousSibling;(3===e.nodeType?e.data.includes("{{")&&!(os(e.parentNode)?Xi.has(e):t.has(n)&&Ki(n,"wcs-t:"))&&(Xi.has(e)||t.get(e)!==e.data):!t.has(e))&&r.push(e)}for(let e of r)e.remove()}let n=Array.from(e.childNodes);os(e)&&n.some(e=>Xi.has(e))&&e.setAttribute(ss,n.map(e=>Xi.has(e)?`{{ ${Xi.get(e)} }}`:8===e.nodeType?`\x3c!--${e.data}--\x3e`:e.textContent).join(""))}ls(9===n.nodeType?n.body:n);let s=document.createElement(Di());s.setAttribute("version",Ri);let o=document.createElement("script");o.type="application/json",o.textContent=function(e){return JSON.stringify(e).replace(/[<>&\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`)}(function(e){let t={};for(let n of Object.keys(e)){if("$"===n[0])continue;let r=Object.getOwnPropertyDescriptor(e,n);void 0!==r.get||void 0!==r.set||"function"==typeof r.value||(t[n]=r.value)}return t}(t.target)),s.append(o);for(let[e,t]of i){if(!e.isConnected)continue;let n=e.parentNode;for(;null!==n&&"svg"!==n.localName&&"foreignObject"!==n.localName;)n=n.parentElement;let r="svg"===n?.localName,i=`wcs-${r?"s":"t"}${as++}`;e.replaceWith(qi(`wcs-p:${i}`));let o=document.importNode(xt(t),!0);for(let e of Array.from(o.querySelectorAll("template")))"http://www.w3.org/2000/svg"===e.namespaceURI&&e.replaceWith(Zi(e,document.createElement("template"),...e.childNodes));if(r){let e=document.createElementNS(n.namespaceURI,"svg");e.append(o),o=e}let l=document.createElement("template");l.id=i,s.append(Zi(t,l,o))}e.before(s)}function cs(e){!function(e){if(null!==e.querySelector(re.tagNames.state))for(let t of Array.from(e.querySelectorAll("input,textarea,select")))if("select"===t.localName){let e=Array.from(t.options);if(t.multiple||e.some(e=>e.hasAttribute("selected"))||e[t.selectedIndex]!==e.find(e=>!e.disabled))for(let t of e)t.toggleAttribute("selected",t.selected)}else"textarea"===t.localName?t.value!==t.defaultValue&&!t.value.includes("{{")&&!Array.from(t.childNodes).some(e=>Xi.has(e))&&(t.textContent=t.value):"checkbox"===t.type||"radio"===t.type?t.toggleAttribute("checked",t.checked):"password"!==t.type&&t.value!==t.defaultValue&&t.setAttribute("value",t.value)}(e);for(let t of Array.from(e.querySelectorAll(`${re.tagNames.state}[enable-ssr]`))){if(t.hasAttribute("mount")||t.hasAttribute("bind-component")||t.previousElementSibling?.localName===Di())continue;let e=t.engine;null!=e&&us(t,e)}}var hs=Symbol.for("wcstack.state.ssr.impl"),ds=new Map,fs=new WeakMap,ps=e=>!0===c.yo?.(e),ms=e=>1===e.nodeType&&!os(e)&&!ps(e),gs=e=>e.u.flat().concat(e.U??[]),ys=e=>{for(let t of gs(e))t.remove()};function bs(e,t,n){let r=/^wcs-\[(?::(\d+))?/.exec(e.data),i=e.previousSibling,s=e.parentNode,o=[],l=e.nextSibling;for(e.remove();null!==l&&!Bi(l,"wcs-]");){let e=l.nextSibling;if(Bi(l,"wcs-|"))o.push([]),l.remove();else{0===o.length&&o.push([]);let n=o[o.length-1];Ki(l,"wcs-[")?e=bs(l,t,n):(n.push(l),ms(l)&&vs(l,t))}l=e}let a={branch:void 0===r[1]?null:Number(r[1]),u:o,U:l??s.appendChild(qi("wcs-]"))},u=gs(a);l=a.U.nextSibling;for(let e of u)n?.push(e),t&&At.add(e);return t&&null!==i?ds.set(i,a):ys(a),l}function vs(e,t){for(let n=e.firstChild;null!==n;)Ki(n,"wcs-[")?n=bs(n,t):(ms(n)&&vs(n,t),n=n.nextSibling)}function ws(e,t,n){let r=e=>{for(let i of Array.from(e.childNodes))if(i.parentNode===e)if(8===i.nodeType){let e=i.data;try{if("wcs-s"===e)i.remove();else if("wcs-e"===e)i.replaceWith("");else if(e.startsWith("wcs-t:")){let t=qi(`@@:${decodeURIComponent(e.slice(6))}`),n=i.nextSibling;for(;null!==n&&!Bi(n,"wcs-/t");){let e=n.nextSibling;n.remove(),n=e}n?.remove(),i.replaceWith(t)}else if(e.startsWith("wcs-p:")){let n=t.querySelector(`template[id="${e.slice(6)}"]`);if(null!==n){let t=i.parentNode,r="s"===e[10]?Zi(n,document.createElementNS(t.namespaceURI,"template"),...document.importNode(n.content.firstChild,!0).childNodes):document.importNode(n,!0);r.removeAttribute("id"),t.replaceChild(r,i)}}}catch{}}else 1===i.nodeType&&!os(i)&&(ps(i)?fs.set(i,{ssr:t,Ae:n}):r(i))};r(e),function(e){for(let t of Array.from(e.querySelectorAll("table > tbody"))){let e=[];for(let n=t.previousSibling;null!==n&&(8===n.nodeType||Es(n)||"template"===n.localName);n=n.previousSibling)e.unshift(n);let n=0,r=0;if(e.forEach((e,t)=>{Ki(e,"wcs-[")?r++:Bi(e,"wcs-]")&&--r<0&&(r=0,n=t+1)}),0===r)continue;let i=0;for(let r=t.firstChild;null!==r;r=r.nextSibling)if(Ki(r,"wcs-["))i++;else if(Bi(r,"wcs-]")&&0===i--){t.prepend(...e.slice(n));break}}}(e),vs(e,n)}function _s(e){let t=fs.get(e);if(void 0===t||(fs.delete(e),ws(e,t.ssr,t.Ae),!t.Ae))return null;let n=c.Ae;return c.Ae=Ts,()=>{c.Ae=n,$s()}}function $s(){for(let e of ds.values())ys(e);ds.clear()}function ks(e){let t=[];for(let n=document.createTreeWalker(e,128);n.nextNode();)t.push(n.currentNode);return t}function Ss(e,t,n,r){let i=null;for(let r of e){let e=r[n];null!==e&&(""===e||t===e||t.startsWith(`${e}.`))&&(null===i||e.length>i[n].length)&&(i=r)}let s=i?.[r];if(null==s)return null;let o=i[n],l=""===o?t:t.slice(o.length+1);return""===s?l:""===l?s:`${s}.${l}`}function Ns(e,t,n){if(Fi()){if(n instanceof Array){for(let e=n.length;e-- >0;)gt(n[e])&&n.splice(e,1);let e=t;if(n.some(yt))Qi.add(e);else if(e.localName.includes("-")&&!ps(e)){let t=new Map;for(let n=document.createTreeWalker(e,133);n.nextNode();)t.set(n.currentNode,n.currentNode.data);Ji.set(e,t)}return}if("string"==typeof n){if(Xi.set(t,n),os(t.parentNode))return;let e=qi(`wcs-t:${encodeURIComponent(n)}`),r=qi("wcs-/t");return t.before(e),void t.after(r)}let r=Gi.get(e);void 0===r&&Gi.set(e,r=new Map),r.set(t,n);let i=t.getRootNode(),s=Vi.get(i);return void 0===s&&Vi.set(i,s=new Set),void s.add(e)}if("string"!=typeof n&&ds.size>0){let e=ds.get(n);void 0!==e&&(ds.delete(n),ds.set(t,e))}}var As=e=>null!==e&&8===e.nodeType&&[re.commentIfPrefix,re.commentElseIfPrefix,re.commentElsePrefix].includes(e.data),Es=e=>3===e.nodeType&&""===e.data.trim(),Cs=e=>(ds.get(e)?.U??e).nextSibling;function xs(e,t){if(t.length!==e.on.childNodes.length)return!1;let n=e.Rn;for(let r=0;r<n.length;r++){let i=n[r],s=e.on,o=t[i[0]];for(let e=0;;){if(s=s.childNodes[i[e]],o?.nodeName!==s.nodeName)return!1;if(++e===i.length)break;o=o.firstChild;for(let t=i[e];t>0&&null!==o;t--)o=Cs(o)}e.mo[r]=o}return!0}function Ts(e,t,n){if(0===ds.size)return null;let r=t,i=0;if(!n){let e=re.commentIfPrefix;if(!Bi(t,e))for(let n=t.previousSibling;null!==n&&1!==n.nodeType&&(As(n)&&i++,!Bi(n,e));n=n.previousSibling);for(let n=t.nextSibling;!ds.has(r)&&null!==n&&!Bi(n,e)&&1!==n.nodeType;n=n.nextSibling)As(n)&&(r=n)}let s=ds.get(r);if(void 0===s)return null;if(!n&&s.branch!==i)return ds.delete(r),ys(s),null;let o=s.u.shift();if(0===s.u.length&&ds.delete(r),s.U?.replaceWith(...Yi(t,r)),s.U=null,void 0===o)return null;let l=[];for(let e=0;e<o.length;e++){let t=ds.get(o[e]);if(l.push(o[e]),void 0!==t)for(;e<o.length&&o[e]!==t.U;)e++}if(!xs(e,l)){let n=(e.Tn?e.root:e.on).cloneNode(!0);l=e.Tn?[n]:[...n.childNodes],xs(e,l),(o[0]??s.u.find(e=>e.length>0)?.[0]??t).before(n);for(let e of o)e.remove()}return l}var Ps={name:"ssr",install(){c.An=Ns,c.ir=_s;let e=c.element;c.element=(t,n)=>{"mounting"===n&&function(e){let t=e.element;if(!t.hasAttribute("enable-ssr")||Fi())return;let n=t.previousElementSibling,r=n?.localName===Di(),i=r?n.getAttribute("version"):null,s=null===i||Hi(i)===Hi(Ri);if(s){let t=e,n=t.we;t.we=(t,r)=>"$connectedCallback"===t?void 0:n.call(e,t,r)}if(!r)return;let o=!s&&parseInt(i)<4,l=/^3\.(\d+)\.(\d+)$/.exec(i),a=null!==l&&(+l[1]-5||+l[2]-3)>=0;s||console.warn(`[@wcstack/state] <${Di()} version="${i}"> does not match ${Ri}: its snapshot is discarded, and the page renders on the client from its own state.${o&&!a?" 3.x output keeps only the path of a text binding outside a template, so such a binding loses its filters: deploy @wcstack/server 4.0 with this client.":""}`);let u=s?n.querySelector('script[type="application/json"]'):null;if(null!==u){let t=JSON.parse(u.textContent||"{}"),n=e.target;for(let e of Object.keys(t)){let r=Object.getOwnPropertyDescriptor(n,e);void 0!==r&&(void 0!==r.get||void 0!==r.set||"function"==typeof r.value)||(n[e]=t[e])}e.hydrated=!0}let h=t.getRootNode();for(let e of Array.from(h.querySelectorAll(`[${ss}]`)))e.textContent=e.getAttribute(ss),e.removeAttribute(ss);let d=9===h.nodeType?h.body:h;o?function(e,t,n){let r=new Map,i=e=>{let t=e.parentElement;for(;null!==t&&!ps(t);)t=t.parentElement;if(null===t)return null;let n=r.get(t);if(void 0===n){let e=i(t),s=t.querySelector(`:scope > ${re.tagNames.state}[bind-component]`).getAttribute("bind-component");r.set(t,n=[]);for(let r of ae(t.getAttribute(re.bindAttributeName)??"")){let t=r.Je;r.ve[0]===s&&n.push([e?Ss(e,t,1,0):t,r.ve.slice(1).join("."),e&&t])}}return n},s=(e,t,n)=>{let r=i(e);if(null===r)return t;let s=/^([^|]*)#m\d+\.([^|]*)$/.exec(t);if(null===s)return n?t:Ss(r,t,0,1)??t;let o=s[1].replace(/#m\d+\./g,"").slice(0,-1);return r.some(e=>""===e[1]&&(e[0]===o||e[2]===o))?s[2]:Ss(r,s[2],2,1)??s[2]};for(let t of ks(e).reverse()){let e=/^@@wcs-(\w+)-start:([\s\S]*)/.exec(t.data);if(null===e)continue;let r=t.nextSibling;for(;null!==r&&!Bi(r,`@@wcs-${e[1]}-end:${e[2]}`);)r=r.nextSibling;if(null!==r){for(;t.nextSibling!==r;)t.nextSibling.remove();r.remove(),t.replaceWith(..."text"===e[1]?[qi(`@@:${s(t,e[2],n)}`)]:[])}}let o=(e,n)=>{for(let r of ks(e)){let e=/^@@wcs-(?:for|if|elseif|else):(\S+)$/.exec(r.data)?.[1],i=Array.from(t.querySelectorAll("template")).find(t=>t.id===e);if(void 0===i)continue;let l=document.importNode(i,!0),a=re.bindAttributeName;l.removeAttribute("id"),l.setAttribute(a,l.getAttribute(a).replace(/^(\s*\w+\s*:\s*)([^\s|]+)/,(e,t,i)=>t+s(n??r,i))),o(l.content,n??r);let u=l.content.firstChild;r.replaceWith(.../^\s*elseif\s*:/.test(u?.getAttribute?.(a)??"")?l.content.childNodes:[l])}};o(e);for(let t of Array.from(e.querySelectorAll("[data-wcs-ssr-id]")))t.removeAttribute("data-wcs-ssr-id")}(d,n,a):ws(d,n,s),n.remove(),s&&(c.Ae=Ts,queueMicrotask(()=>{$s(),c.Ae=null}))}(t),e?.(t,n)},function(){let e=globalThis;e[hs]={build:cs,reset(){as=0}},void 0===e[Ui]&&(e[Ui]={protocol:"wcs-ssr-snapshot",version:1,build:t=>e[hs].build(t),reset:()=>e[hs].reset()})}(),c.Eo=h(c.Eo,zi);for(let e of Zt())zi(e)}},Os="__WCSTACK_DEVTOOLS_HOOK__",Ms=null,Ls=new Set,Is=(e,t,n)=>({absolutePathInfo:{pathInfo:{path:t.t},stateElement:e.element},listIndex:null===n?null:{indexes:e._(n)}}),js=new WeakMap,Rs=0,Hs=new WeakMap;function Ws(e){if(null===Ms)return;let t=Hs.get(e),n=Ls.has(e)?function(e,t){let n=new Map,r=new Set,i=(r,i,s,o,l,a)=>{if(5===r)return;let u=function(e,t){return 0===e?"textContent":2===e?`class.${t}`:3===e?`attr.${t}`:4===e?`style.${t}`:t}(r,i),c=0===o.n?null:l,h=`${(e=>{let t=js.get(e);return void 0===t&&js.set(e,t=++Rs),t})(s)}|${u}|${o.t}|${null===c?"":e._(c).join(",")}`;if(n.has(h))return;let d=t?.get(h);n.set(h,d??{binding:{propName:u,statePathName:o.t,bindingType:a,node:s,replaceNode:s},absoluteAddress:Is(e,o,c)})},s=e=>i(e.i,e.name,e.a,e.o,e.r,e.en()),o=e=>{if(!r.has(e)){if(r.add(e),null!==e.fe)for(let t of e.fe)s(t);if(e instanceof Xe&&null!==e.ae){let t=e.A.Ke;for(let n=0;n<t.length;n++){let r=e.W?.[n];void 0!==r?s(r):i(t[n].i,t[n].name,e.ae[2*n],t[n].o,e.r,0===t[n].i?"text":"prop")}}if(null!==e.h)for(let t of e.h)l(t)}},l=e=>{if(!r.has(e))if(r.add(e),e instanceof lt){i(-1,"for",e.S,e.l.o,e.l.re,"for");for(let t of e.Ee)o(t)}else null!==e.O&&o(e.O)};for(let t of e.ie.values())for(let e of t)s(e),null!==e.M&&l(e.M);for(let t of e.ee.values())if(null!==t.$&&l(t.$),null!==t.L)for(let e of t.L)l(e);return n}(e,t):new Map;if(void 0!==t)for(let[e,r]of t)n.has(e)||Ms({type:"state:binding-removed",...r});for(let[e,r]of n)(void 0===t||!t.has(e))&&Ms({type:"state:binding-added",...r});Hs.set(e,n)}function zs(e){let t=It.get(e);if(void 0===t)throw new Error("[@wcstack/state] devtools: no state tree on this root");return t}function Ds(e){let t=new Set,n=new Set,r=new Set,i=new Set;for(let s of e.B.all()){for(let e=1;e<=s.n;e++)t.add(s.f[e].t);"*"===s.s&&n.add(s.t),null!==s.getter&&r.add(s.t),null!==s.oe&&i.add(s.t)}let s=e.target;return{rootNode:e.root,element:e.element,paths:{list:t,element:n,getter:r,setter:i},commandTokenNames:new Set(Object.keys(e.commands)),eventTokenNames:new Set(e.Ne.keys()),staticDependency:new Map,dynamicDependency:new Map,watchPaths:null!==s.$watch&&"object"==typeof s.$watch?new Set(Object.keys(s.$watch)):null,keyedListPaths:null!==s.$listKeys&&"object"==typeof s.$listKeys?new Set(Object.keys(s.$listKeys)):null}}var Us=new WeakSet,Fs=new WeakMap;function qs(e,t){if(("mounting"===t||"reset"===t)&&function(e){let t=(t,n)=>{if(Us.has(t))return;Us.add(t);let r=t.emit;t.emit=(...i)=>(null!==Ms&&Ms({type:"state:token-emit",kind:n,tokenName:t.name,args:i,subscriberCount:t.size,stateElement:e.element}),r.apply(t,i))};for(let n of Object.values(e.commands))t(n,"command");for(let n of e.Ne.values())t(n,"event")}(e),"connected"===t){if(Ls.has(e))return;Ls.add(e),Ms?.({type:"state:element-registered",rootNode:e.root,element:e.element}),Ws(e)}else"disconnected"===t&&(Ls.delete(e),Ws(e),Ms?.({type:"state:element-unregistered",rootNode:e.root,element:e.element}))}function Bs(e,t,n,r,i,s){if(null===Ms)return;let o=Is(e,t,0===t.n?null:n),l=Fs.get(e);void 0===l&&Fs.set(e,l=new Set),l.add(o),s&&Ms({type:"state:write",absoluteAddress:o,value:i,oldValue:r,hasOldValue:!0})}function Ks(e){if(null===Ms)return;let t=Fs.get(e);Fs.delete(e),void 0!==t&&Ms({type:"state:update-batch",addresses:t}),Ws(e)}function Gs(e,t,n){Ms?.({type:"state:binding-apply-error",path:n.o.t,bindingType:n.en(),error:t})}!function(e){for(let t of e)g.has(t.name)||(g.add(t.name),t.install())}([ln,Ln,sr,fr,_i,ji,Ps,{name:"devtools",install(){c.element=h(c.element,qs),c.he=h(c.he,Bs),c.Te=h(c.Te,Ks),c.Ve=h(c.Ve,Gs),function(){if(typeof document>"u"||document.documentElement?.hasAttribute("data-wcs-server"))return;let e=globalThis,t=e[Os]??(e[Os]=function(){let e=new Map,t=new Set,n=e=>{0===t.size?e._setSink(null):e._setSink(n=>{for(let r of t)r.onEvent?.(e.id,n)})};return{version:2,sources:e,register(r){if(!e.has(r.id)){e.set(r.id,r),n(r);for(let e of t)e.onSourceRegistered?.(r)}},unregister(n){let r=e.get(n);if(void 0!==r){r._setSink(null),e.delete(n);for(let e of t)e.onSourceUnregistered?.(n)}},addListener(r){t.add(r);for(let t of e.values())n(t),r.onSourceRegistered?.(t);return()=>{if(t.delete(r))for(let t of e.values())n(t)}}}}());2!==t.version&&console.warn(`[@wcstack/state] devtools hook registry version ${t.version}, expected 2: keeping the existing one.`),t.register({id:`state:${Math.random().toString(36).slice(2,10)}`,kind:"state",packageVersion:Ri,getStateElements:()=>[...Ls].map(Ds),overlays:()=>[],keyedSubscriptions:e=>function(e){let t=[];for(let n of e.B.all()){let r=n.q,i=n.Fe?.length??0;if((null===r||0===r.size)&&0===i)continue;let s,o=0;if(null!==r)for(let e of r.values())o+=e.size;try{s=0===n.n?e.v(n,null):void 0}catch{s=void 0}t.push({path:n.t,tracked:!1,rows:o,keys:null===r?0:r.size,lists:i,lastValue:s})}return t}(zs(e)),keys(e){let t=zs(e).target;return Object.keys(t).filter(e=>{if(e.includes("*")||"$"===e[0])return!1;let n=Object.getOwnPropertyDescriptor(t,e);return void 0!==n.get||"function"!=typeof n.value})},read(e,t,n){let r;return zs(e).element.createState("readonly",e=>{r=e.$resolve(t,n??[])}),r},write(e,t,n,r){zs(e).element.createState("writable",e=>{e.$resolve(t,r??[],n)})},_setSink(e){let t=null===Ms&&null!==e;Ms=e,null===e&&(Hs=new WeakMap),c.nt=e&&((e,t)=>Ms?.({...t,stateElement:e.element})),t&&queueMicrotask(()=>{for(let e of Ls)Ws(e)})}})}()}}]),function(e=customElements){(function(){let e=globalThis;void 0===e[Wt]&&(e[Wt]={protocol:"wcs-binder",version:1,bind:Ft})})(),Zt().includes(e)||Yt.push(new WeakRef(e));let t=re.tagNames.state;void 0===e.get(t)&&e.define(t,class extends Xt{}),c.Eo?.(e)}();const Vs={route:"wcs-route",router:"wcs-router",outlet:"wcs-outlet",layout:"wcs-layout",layoutOutlet:"wcs-layout-outlet",link:"wcs-link",head:"wcs-head",guardHandler:"wcs-guard-handler"},Js=!1,Qs=[".html"];function Xs(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function Ys(e,t){if(t&&"cause"in t)throw new Error(`[@wcstack/router] ${e}`,{cause:t.cause});throw new Error(`[@wcstack/router] ${e}`)}let Zs=class extends Error{fallbackPath;constructor(e,t){super(e),this.fallbackPath=t}};const eo={int:{typeName:"int",pattern:/^-?\d+$/,parse(e){if(this.pattern.test(e))return parseInt(e,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(e){if(this.pattern.test(e))return parseFloat(e)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(e){if(this.pattern.test(e))return"true"===e||"1"===e}},uuid:{typeName:"uuid",pattern:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,parse(e){if(this.pattern.test(e))return e}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(e){if(this.pattern.test(e))return e}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(e){if(!this.pattern.test(e))return;const[t,n,r]=e.split("-").map(Number),i=new Date(t,n-1,r);return i.getFullYear()===t&&i.getMonth()===n-1&&i.getDate()===r?i:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(e){if(this.pattern.test(e))return e}}};function to(e){const t={};for(const[n,r]of new URLSearchParams(e))t[n]=r;return Object.freeze(t)}function no(e,t){const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const r of n){if(!Object.prototype.hasOwnProperty.call(t,r))return!1;if(e[r]!==t[r])return!1}return!0}const ro={static:2,param:1,"catch-all":0};let io=class extends EventTarget{_target;_parentCore=null;_path="";_name="";_isFallbackRoute=!1;_segmentInfos=[];_absoluteSegmentInfos;_paramNames;_absoluteParamNames;_weight;_absoluteWeight;_segmentCount;_params={};_typedParams={};_active=!1;_hasGuard=!1;_guardHandler=null;_guardFallbackPath="";_waitForSetGuardHandler=null;_resolveSetGuardHandler=null;_guardHandlerLoadFailed=!1;constructor(e){super(),this._target=e??this}get parentCore(){return this._parentCore}set parentCore(e){this._parentCore=e}get path(){return this._path}get name(){return this._name}get isFallbackRoute(){return this._isFallbackRoute}get isRelative(){return!this._path.startsWith("/")}get segmentInfos(){return this._segmentInfos}_checkParentCore(e,t){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&Ys(`${Vs.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&Ys(`${Vs.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?e(this._parentCore):t()}get absolutePath(){return this._checkParentCore(e=>{const t=e.absolutePath;return t.endsWith("/")?t+this._path:t+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(e=>[...e.absoluteSegmentInfos,...this._segmentInfos],()=>[...this._segmentInfos])),this._absoluteSegmentInfos}get params(){return this._params}get typedParams(){return this._typedParams}get active(){return this._active}get paramNames(){if(void 0===this._paramNames){const e=[];for(const t of this._segmentInfos)t.paramName&&e.push(t.paramName);this._paramNames=e}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(e=>[...e.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let e=0;for(const t of this._segmentInfos)e+=ro[t.type];this._weight=e}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(e=>e.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let e=0;for(const t of this._segmentInfos)"catch-all"!==t.type&&e++;this._segmentCount=""===this._path?0:e}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(e=>e.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(e,t={}){this._segmentInfos=[],this._absoluteSegmentInfos=void 0,this._paramNames=void 0,this._absoluteParamNames=void 0,this._weight=void 0,this._absoluteWeight=void 0,this._segmentCount=void 0,this._path=e,this._name=t.name||"",this._isFallbackRoute=t.isFallback||!1,t.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const n=e.split("/");for(let e=0;e<n.length;e++){const r=n[e];if(!(""===r&&e===n.length-1&&e>0)){if("*"===r){this._segmentInfos.push({type:"catch-all",segmentText:r,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(r.startsWith(":")){const e=r.match(/^:([^()]+)(\(([^)]+)\))?$/);let t,n="any";e?(t=e[1],e[3]&&Object.keys(eo).includes(e[3])&&(n=e[3])):t=r.substring(1),this._segmentInfos.push({type:"param",segmentText:r,paramName:t,pattern:new RegExp("^([^\\/]+)$"),paramType:n})}else""===r&&t.isIndex||this._segmentInfos.push({type:"static",segmentText:r,paramName:null,pattern:new RegExp(`^${r}$`)})}}this._hasGuard=t.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=t.guardFallback||"/",this._waitForSetGuardHandler=new Promise(e=>{this._resolveSetGuardHandler=e}))}setParams(e,t){const n=this._active;this._params=e,this._typedParams=t,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:e,typedParams:t},bubbles:!0})),n||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const e=this._active;this._params={},this._typedParams={},this._active=!1,e&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(e){for(const t of this.paramNames)if(this._params[t]!==e[t])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||Ys(`${Vs.route} has no guardHandler.`),this._guardHandler}set guardHandler(e){this._guardHandler=e,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(e){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const t=e.path,n=e.lastPath,r=await this._guardHandler(t,n,function(e){return Object.freeze({params:Object.freeze({...e.params}),typedParams:Object.freeze({...e.typedParams}),searchParams:to(e.search??""),routeName:e.routes[e.routes.length-1]?.name??""})}(e));if("string"==typeof r&&""!==r)throw new Zs("Navigation cancelled by guard.",r);if(!r)throw new Zs("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof r?r:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new Zs("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}};const so="data-wcs-ssr",oo="data-wcs-ssr-link",lo="@@wcs-route-ph:",ao="@@wcs-route-start:",uo="@@wcs-route-end:";let co=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=Xs();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new io(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||Ys(`${Vs.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get endMarker(){return void 0===this._endMarker&&(this._endMarker=document.createComment(`${uo}${this.absolutePath}`)),this._endMarker}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(e,t){for(this._childNodeArray=[...e],t&&(this._endMarker=t);this.firstChild;)this.removeChild(this.firstChild)}get routes(){return void 0===this._routes&&(this._routes=this.routeParentNode?this.routeParentNode.routes.concat(this):[this]),this._routes}get childIndex(){return this._childIndex}get path(){return this._core.path}get name(){return this._core.name}get isRelative(){return this._core.isRelative}get absolutePath(){return this._core.absolutePath}get segmentInfos(){return this._core.segmentInfos}get absoluteSegmentInfos(){return this._core.absoluteSegmentInfos}get params(){return this._core.params}get typedParams(){return this._core.typedParams}get paramNames(){return this._core.paramNames}get absoluteParamNames(){return this._core.absoluteParamNames}get weight(){return this._core.weight}get absoluteWeight(){return this._core.absoluteWeight}get segmentCount(){return this._core.segmentCount}get absoluteSegmentCount(){return this._core.absoluteSegmentCount}get fullpath(){return this.absolutePath}get hasGuard(){return this._core.hasGuard}get guardHandler(){return this._core.guardHandler}set guardHandler(e){this._core.guardHandler=e}setParams(e,t){this._core.setParams(e,t)}clearParams(){this._core.clearParams()}shouldChange(e){return this._core.shouldChange(e)}async guardCheck(e){return this._core.guardCheck(e)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}testAncestorNode(e){let t=this._routeParentNode;for(;t;){if(t===e)return!0;t=t.routeParentNode}return!1}initialize(e,t){if(this._initialized)return;let n;this._initialized=!0;let r=!1,i=!1;this.hasAttribute("path")?n=this.getAttribute("path")||"":this.hasAttribute("index")?(n="",r=!0):this.hasAttribute("fallback")?(n="",i=!0):Ys(`${Vs.route} should have a "path" or "index" attribute.`),this._routerNode=e,this._routeParentNode=t;const s=t||e;s.routeChildNodes.push(this),this._childIndex=s.routeChildNodes.length-1,i&&(t&&Ys(`${Vs.route} with fallback attribute must be a direct child of ${Vs.router}.`),e.fallbackRoute&&Ys(`${Vs.router} can have only one fallback route.`),e.fallbackRoute=this),t&&(this._core.parentCore=t._core),this._core.parsePath(n,{isIndex:r,isFallback:i,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}};const ho=Symbol.for("wcstack.trustedTypes.policy"),fo=Symbol.for("wcstack.trustedTypes.internal"),po="wcstack";function mo(){const e=globalThis[ho];return null===e||"object"!=typeof e?null:e}let go=!1;function yo(e){const t=function(){const e=globalThis,t=e[fo];if(void 0!==t)return t;const n=globalThis.trustedTypes;let r=null;if(n&&"function"==typeof n.createPolicy)try{r=n.createPolicy(po,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){"function"!=typeof mo()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${po}". Allow it in the CSP (\`trusted-types ${po};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,e)}return e[fo]=r,r}(),n=t?.createHTML;if("function"==typeof n)return n.call(t,e);if(!("trustedTypes"in globalThis))return e;const r=mo(),i=r?.createHTML;return"function"==typeof i?(go||(go=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${po}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${po};\` in the CSP to avoid this. See docs/csp.md section 7.`)),i.call(r,e)):e}const bo=new Map;let vo=class extends HTMLElement{_uuid=Xs();constructor(){super()}async _loadTemplateFromSource(e){try{const t=await fetch(e);t.ok||Ys(`${Vs.layout} failed to fetch layout from source: ${e}, status: ${t.status}`);const n=await t.text();return bo.set(e,n),n}catch(t){Ys(`${Vs.layout} failed to load layout from source: ${e}, error: ${t}`,{cause:t})}}_loadTemplateFromDocument(e){const t=document.getElementById(`${e}`);return t&&t instanceof HTMLTemplateElement?t.innerHTML:null}async loadTemplate(){const e=this.getAttribute("src"),t=this.getAttribute("layout");e&&t&&console.warn(`${Vs.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(e)bo.has(e)?n.innerHTML=yo(bo.get(e)||""):n.innerHTML=yo(await this._loadTemplateFromSource(e)||"");else if(t){const e=this._loadTemplateFromDocument(t);e?n.innerHTML=yo(e):console.warn(`${Vs.layout} could not find template with id "${t}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&Js}get name(){return this.getAttribute("name")||""}};class wo extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||Ys(`${Vs.outlet} has no routesNode.`),this._routesNode}set routesNode(e){this._routesNode=e}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(e){this._lastRoutes=[...e]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&Js}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const _o=new Set(["props","states","attr",""]);function $o(e,t,n){for(const[r,i]of Object.entries(t))switch(n){case"props":e.props={...e.props,[r]:i};break;case"states":e.states={...e.states,[r]:i};break;case"attr":null==i?e.removeAttribute(r):e.setAttribute(r,String(i));break;case"":e[r]=i}}function ko(e,t){e.hasAttribute("data-bind")||Ys(`${e.tagName} has no 'data-bind' attribute.`);const n=e.getAttribute("data-bind")||"";_o.has(n)||Ys(`${e.tagName} has invalid 'data-bind' attribute: ${n}`);const r=n,i=function(e){const t=e.tagName.toLowerCase();if(t.includes("-"))return t;const n=e.getAttribute("is");return n&&n.includes("-")?n:null}(e);i&&void 0===customElements.get(i)?customElements.whenDefined(i).then(()=>{e.isConnected&&$o(e,t,r)}).catch(()=>{Ys(`Failed to define custom element: ${i}`)}):$o(e,t,r)}const So=Symbol.for("wcstack.binder");function No(){const e=globalThis[So];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}const Ao=Symbol.for("wcstack.binder.pending"),Eo=Symbol.for("wcstack.binder.taken");function Co(){const e=globalThis;let t=e[Eo];return void 0===t&&(t=new WeakSet,e[Eo]=t),t}function xo(e,t){const n=No();return null===n?(function(){const e=globalThis;let t=e[Ao];return void 0===t&&(t=[],e[Ao]=t),t}().push(e),!1):(Co().add(e),n.bind(e,t),!0)}const To={range:!0};function Po(e,t){for(const n of e.routeChildNodes)t.add(n.placeHolder).add(n.endMarker),Po(n,t);return t}function Oo(e){const t=e.placeHolder,n=e.endMarker,r=null!==n.parentNode&&n.parentNode===t.parentNode&&!!(4&t.compareDocumentPosition(n)),i=r?null:Po(e,new Set),s=[];let o=0;for(let l=t.nextSibling;null!==l&&l!==n&&(null===i||8!==l.nodeType||!/^@@(route:|wcs-route-)/.test(l.data)||i.has(l));l=l.nextSibling)s.push(l),(r||e.childNodeArray.includes(l))&&(o=s.length);return s.length=o,s}let Mo=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||Ys(`${Vs.layoutOutlet} has no layout.`),this._layout}set layout(e){this._layout=e,this.setAttribute("name",e.name)}get name(){return this.layout.name}async _initialize(){this._initializing=!0;try{this._initialized=!0,this.layout.enableShadowRoot&&!this.shadowRoot&&this.attachShadow({mode:"open"});const e=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(e.content.cloneNode(!0));for(const e of Array.from(this.layout.childNodes))this._layoutChildNodes.push(e),this.appendChild(e)}else{const t=e.content.cloneNode(!0),n=new Map;t.querySelectorAll("slot").forEach(e=>{const t=e.getAttribute("name")||"";n.has(t)?console.warn(`${Vs.layoutOutlet} duplicate slot name "${t}" in layout template.`):n.set(t,e)});const r=new Map,i=document.createDocumentFragment();for(const e of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(e),e instanceof Element){const t=e.getAttribute("slot")||"";if(t.length>0&&n.has(t)){r.has(t)||r.set(t,document.createDocumentFragment()),r.get(t)?.appendChild(e);continue}}i.appendChild(e)}for(const[e,t]of n){const n=r.get(e);n&&t.replaceWith(n)}const s=n.get("");s&&s.replaceWith(i),this.appendChild(t)}!function(e){if(null!==No())for(const t of e)1===t.nodeType&&xo(t,To)}(Array.from(this.childNodes))}finally{this._initializing=!1}}async connectedCallback(){this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected)}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(e){for(const t of this._layoutChildNodes)t instanceof Element&&(t.querySelectorAll("[data-bind]").forEach(t=>{ko(t,e)}),t.hasAttribute("data-bind")&&ko(t,e))}};function Lo(){return document.createElement(Vs.layoutOutlet)}const Io="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function jo(e,t){(async function(e,t){let n=null,r=null;const i=t.uuid||"",s=`\n//# sourceURL=${i?`wcs-guard-handler:${i}`:"wcs-guard-handler"}\n`,o=e.text+s;let l=!1;const a=e=>{e.effectiveDirective.startsWith("script-src")&&(l=!0)};document.addEventListener("securitypolicyviolation",a);try{if("function"==typeof URL.createObjectURL){const t=new Blob([o],{type:"application/javascript"}),i=URL.createObjectURL(t);try{n=await(import(i))}catch(e){r=e}finally{URL.revokeObjectURL(i)}}if(!n){const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(o)));try{n=await(import(`data:application/javascript;base64,${t}`))}catch(e){await new Promise(e=>setTimeout(e)),Ys(function(e,t,n){return n?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/router, or allow blob: in script-src. See ${Io}`:`loadGuardHandler: failed to import guard script. data: URL error: ${e?.message??String(e)}`+(t?`. Blob URL error: ${t?.message??String(t)}`:"")+`. If this page sets a Content-Security-Policy, see ${Io}`}(e,r,l),{cause:r??e})}}}finally{document.removeEventListener("securitypolicyviolation",a)}return n&&"function"==typeof n.default?n.default:null})(e,t).then(e=>{e?t.guardHandler=e:t.notifyGuardHandlerLoadFailed()}).catch(e=>{console.error("loadGuardHandler failed:",e),t.notifyGuardHandlerLoadFailed()})}function Ro(e,t){let n=e.get(t.absolutePath);n||(n=[]);for(const e of n)if(!t.testAncestorNode(e)){console.warn(`Duplicate route path detected: '${t.absolutePath}' (defined as '${t.path}')`);break}n.push(t),1===n.length&&e.set(t.absolutePath,n)}async function Ho(e,t,n,r){const i=n.length>0?n[n.length-1]:null,s=document.createDocumentFragment(),o=Array.from(t.childNodes);for(const t of o)if(t.nodeType===Node.ELEMENT_NODE){let o=t,l=t;const a=l.tagName.toLowerCase();if(a===Vs.route){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const s=document.importNode(l,!0);customElements.upgrade(s),s.appendChild(t);const a=s;a.initialize(e,i),Ro(r,a),n.push(a),o=a.placeHolder,l=a}else{if(a===Vs.guardHandler){if(n.length>0){const e=n[n.length-1],t=l.querySelector('script[type="module"]');t&&jo(t,e)}continue}if("template"===a){s.appendChild(l);continue}if(a===Vs.layout){const e=document.createDocumentFragment();for(const t of Array.from(l.childNodes))e.appendChild(t);const t=document.importNode(l,!0);customElements.upgrade(t),t.appendChild(e);const n=t,r=Lo();r.layout=n,o=r,l=t}}const u=await Ho(e,l,n,r);l.replaceChildren(),l.appendChild(u),s.appendChild(o)}else s.appendChild(t);return s}async function Wo(e){const t=new Map;return await Ho(e,e.template.content,[],t)}function zo(e){return!1!==e.checkVisibility?.()}function Do(e,t,n,r){const i=function(e,t,n){const r={},i={};let s=!0,o=!1,l=0,a=0;for(;l<e.absoluteSegmentInfos.length;){const t=e.absoluteSegmentInfos[l];if(t.isIndex){l++;continue}if(0===l&&""===t.segmentText&&"static"===t.type){l++;continue}const u=n[a];if(void 0===u){s=!1;break}let c=!1;if("param"===t.type){const e=t.paramType||"any",n=eo[e].parse(u);void 0!==n&&(t.paramName&&(r[t.paramName]=u,i[t.paramName]=n),c=!0)}else c=null!==t.pattern.exec(u);if(!c){s=!1;break}if("catch-all"===t.type){const e=n.slice(a).join("/");r["*"]=e,i["*"]=e,o=!0;break}l++,a++}let u=!1;return s&&(o||l===e.absoluteSegmentInfos.length&&a===n.length)&&(u=!0),u?{path:t,routes:e.routes,params:r,typedParams:i,lastPath:""}:null}(e,t,n);i&&r.push(i);for(const i of e.routeChildNodes)Do(i,t,n,r)}function Uo(e,t){const n=e.routeChildNodes,r=[],i=t.split("/"),s=i.filter((e,t)=>!(0===t&&""===e||t===i.length-1&&""===e&&i.length>1));for(const e of n)Do(e,t,s,r);return r.sort((e,t)=>{const n=e.routes.at(-1),r=t.routes.at(-1),i=n.absoluteSegmentCount-r.absoluteSegmentCount;if(0!==i)return-i;const s=n.absoluteWeight-r.absoluteWeight;return 0!==s?-s:n.childIndex-r.childIndex}),r.length>0?r[0]:null}let Fo=null,qo=null;function Bo(){const e=Qs;return 0===e.length?null:(Fo===e&&qo||(Fo=e,qo=new RegExp(`\\/[^/]+(?:${e.map(e=>e.replace(/\./g,"\\.")).join("|")})$`,"i")),qo)}function Ko(e){let t=e||"/";t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/");const n=Bo();return n&&(t=t.replace(n,"")),""===t&&(t="/"),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Go(e,t){let n=e;return""!==t&&(e===t?n="":e.startsWith(t+"/")&&(n=e.slice(t.length))),""===n?"/":n}function Vo(e){let t=e||"";if(!t)return"";t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/");const n=Bo();return n&&(t=t.replace(n,"")),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),"/"===t?"":t}function Jo(e){if(null!==e.held)return;const t=Oo(e),n=new Set(t),r=[...t,...e.childNodeArray];let i=null;for(const s of e.childNodeArray)n.has(s)?i=s:null===s.parentNode||r.some(e=>e!==s&&e.contains(s))||(t.splice(null===i?0:t.indexOf(i)+1,0,s),n.add(s),i=s);const s=document.createDocumentFragment();!function(e,t){const n=t.map(e=>e.parentNode);for(let r=0;r<t.length;r++)t[r].parentNode===n[r]&&e.appendChild(t[r])}(s,t),s.appendChild(e.endMarker),e.held=s}function Qo(e){e.clearParams(),Jo(e)}function Xo(e,t){const n={},r={};for(const i of e.paramNames)n[i]=t.params[i],r[i]=t.typedParams[i];e.setParams(n,r);for(const t of e.childNodeArray)if(t.nodeType===Node.ELEMENT_NODE){const n=t;n.querySelectorAll("[data-bind]").forEach(t=>{ko(t,e.typedParams)}),n.hasAttribute("data-bind")&&ko(n,e.typedParams),n.querySelectorAll(Vs.layoutOutlet).forEach(t=>{t.assignParams(e.typedParams)}),n.tagName.toLowerCase()===Vs.layoutOutlet&&n.assignParams(e.typedParams)}}const Yo=new WeakSet;function Zo(e){const t=e.placeHolder;null!==t.parentNode&&(Yo.has(e)||null!==e.endMarker.parentNode?(Jo(e),t.after(e.held),e.held=null):t.after(...e.childNodeArray,e.endMarker),Yo.add(e))}const el=Symbol.for("wcstack.transition-runner");const tl=new WeakSet,nl="data-wcs";function rl(e,t,n){!tl.has(e)&&function(e){return e.hasAttribute(nl)||null!==e.querySelector(`[${nl}]`)}(e)&&(tl.add(e),function(e){"complete"===document.readyState?e():window.addEventListener("load",e,{once:!0})}(()=>{var r;null!==No()||(r=e,Co().has(r))||console.warn(`[@wcstack/router] ${t} contains ${nl} bindings that will never be applied. A binding exists only for nodes that were in the document when @wcstack/state built its bindings, and these nodes were not. They will render empty. ${n}`)}))}function il(e){for(const t of e.childNodeArray)if(1===t.nodeType){if(t.isConnected){if(xo(t,To))continue}else if(null!==No())continue;rl(t,`<${t.tagName.toLowerCase()}> inside a route`,'Load @wcstack/state on this page, or render data-driven markup outside <wcs-router> — bind the router\'s `path` into state and gate the markup with <template data-wcs="if: …">. See examples/router-i18n.')}}async function sl(e,t){try{let e=null;for(const n of t.routes){const r=await n.guardCheck(t);r&&(e=null===e?r:Object.assign({},e,r))}t.data=e}catch(t){if(t instanceof Zs)return console.warn(`Navigation cancelled: ${t.message}. Redirecting to ${t.fallbackPath}`),queueMicrotask(()=>{e.navigate(t.fallbackPath).catch(e=>{console.error("Fallback navigation failed:",e)})}),!1;throw t}return!0}async function ol(e,t,n,r,i=""){const s=Go(n,e.basename);if(e.isSameMatch(s))return e.commitNavigation({params:e.params,typedParams:e.typedParams,routeName:e.routeName,data:e.data,search:i,path:s}),!0;let o=Uo(e,s);o||(e.fallbackRoute?o={routes:[e.fallbackRoute],params:{},typedParams:{},path:s,lastPath:r}:Ys(`${Vs.router} No route matched for path: ${s}`)),o.lastPath=r,o.search=i;const l=t.lastRoutes,a=await async function(e,t,n){if(!await sl(e,t))return!1;const r=new Set(t.routes),i=new Set(n),s=()=>{for(const e of n)r.has(e)||Qo(e);const e=[];for(const n of t.routes)(e.length>0||!i.has(n)||n.shouldChange(t.params))&&(e.push(n),Xo(n,t));let s=!1;for(const t of e){const e=i.has(t);e&&s||Zo(t),s||=e,n.length>0&&!e&&il(t)}};let o;return 0===n.length?s():o=function(e,t,n){const r=function(e){const t=globalThis[el];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}(e);if(null!==r)return r.run(t,{source:e,types:n});t()}("router",s),void 0!==o&&await o,!0}(e,o,l);return!!a&&(e.commitNavigation({params:o.params,typedParams:o.typedParams,routeName:o.routes[o.routes.length-1]?.name??"",data:o.data??null,search:i,path:s}),t.lastRoutes=o.routes,l.length>0&&function(e,t){if("title"===e.announcePolicy){const t=e.a11yRegion;null!==t&&(t.textContent=document.title)}if("heading"===e.focusPolicy){const e=function(e){for(const t of e){if(t.nodeType!==Node.ELEMENT_NODE)continue;const e=t;if(/^H[1-6]$/.test(e.tagName)){if(zo(e))return e}else for(const t of e.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(zo(t))return t}return null}(t.routes[t.routes.length-1].childNodeArray);if(null!==e)e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1"),e.focus();else{const e=document.querySelector("[autofocus]");null!==e?e.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}(e,o),!0)}function ll(){const e=window.navigation;return e?"function"!=typeof e.addEventListener||"function"!=typeof e.removeEventListener?null:e:null}function al(e){let t=e,n="";const r=t.indexOf("#");r>=0&&(n=t.slice(r),t=t.slice(0,r));let i="";const s=t.indexOf("?");return s>=0&&(i=t.slice(s),t=t.slice(0,s)),{pathname:t,search:i,hash:n}}function ul(e){return"?"===e?"":e}function cl(e,t){let n=Object.getPrototypeOf(e);for(;null!==n;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return"function"==typeof e.get||"function"==typeof e.set;n=Object.getPrototypeOf(n)}return!1}function hl(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const dl=Object.freeze({});class fl extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"navigateUrl",event:"wcs-router:navigate-url-changed",semantics:"state"},{name:"replaceUrl",event:"wcs-router:replace-url-changed",semantics:"state"},{name:"path",event:"wcs-router:path-changed",semantics:"state"},{name:"params",event:"wcs-router:params-changed",semantics:"state",getter:e=>e.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:e=>e.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"},{name:"data",event:"wcs-router:data-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=dl;_typedParams=dl;_searchParams=dl;_routeName="";_data=null;_hasCommitted=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((e,t)=>{this._resolveConnectedCallback=e,this._rejectConnectedCallback=t}),this._connectedCallbackPromise.catch(()=>{})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get a11yRegion(){return this._a11yRegion}get focusPolicy(){return"heading"===this.getAttribute("focus")?"heading":null}get announcePolicy(){return"title"===this.getAttribute("announce")?"title":null}_ensureA11yRegion(){if(null!==this._a11yRegion)return;const e=document.createElement("div");e.setAttribute("role","status"),e.style.position="absolute",e.style.width="1px",e.style.height="1px",e.style.overflow="hidden",e.style.clipPath="inset(50%)",e.style.whiteSpace="nowrap",this.appendChild(e),this._a11yRegion=e}_normalizePathname(e){return Ko(e)}_normalizeBasename(e){return Vo(e)}_joinInternalPath(e,t){const n=this._normalizeBasename(e);let r=t.startsWith("/")?t:"/"+t;return r=this._normalizePathname(r),n?"/"===r?n+"/":n+r:r}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let e=new URL(document.baseURI).pathname||"/";return"/"===e?"":this._normalizeBasename(e)}get basename(){return this._basename}_getOutlet(){const e=this.nextElementSibling;if(e&&e.matches(Vs.outlet))return e;const t=document.createElement(Vs.outlet);return this.parentNode?this.parentNode.insertBefore(t,this.nextSibling):document.body.appendChild(t),t}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||Ys(`${Vs.router} has no outlet.`),this._outlet}get template(){return this._template||Ys(`${Vs.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(e){const t=this._path!==e;this._path=e,t&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:e,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}get data(){return this._data}isSameMatch(e){return!!this._hasCommitted&&this._path===e}commitNavigation(e){const t=Object.freeze({...e.params}),n=Object.freeze({...e.typedParams}),r=to(e.search),i=e.data??null,s=this._data!==i,o=!no(this._params,t),l=this._routeName!==e.routeName,a=!no(this._searchParams,r),u=this._path!==e.path;s&&(this._data=i),o&&(this._params=t,this._typedParams=n),l&&(this._routeName=e.routeName),a&&(this._searchParams=r),this._path=e.path,this._hasCommitted=!0,s&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),o&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),l&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),a&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),u&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:e.path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(e){this._fallbackRoute=e}get navigateUrl(){return this._navigateUrl}set navigateUrl(e){null!=e&&""!==e&&this._navigateUrl!==e&&(this._navigateUrl=e,this.navigate(e).catch(e=>{console.error(`${Vs.router} navigate failed:`,e)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(e){null!=e&&""!==e&&this._replaceUrl!==e&&(this._replaceUrl=e,this.replace(e).catch(e=>{console.error(`${Vs.router} replace failed:`,e)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(e){await this._performNavigation(e,!1)}async replace(e){await this._performNavigation(e,!0)}async _performNavigation(e,t){const n=al(e),r=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,i=r+ul(n.search)+n.hash,s=ll();if(s?.navigate){const e=t?s.navigate(i,{history:"replace"}):s.navigate(i);await(e?.finished)}else{t?history.replaceState(null,"",i):history.pushState(null,"",i);const e=this._normalizePathname(r),s=this.isSameMatch(Go(e,this._basename));await ol(this,this.outlet,e,this._path,ul(n.search))&&!s&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(e){return""===this._basename||e===this._basename||e.startsWith(this._basename+"/")}_onNavigateFunc(e){if(!e.canIntercept||e.hashChange||null!==e.downloadRequest)return;const t=new URL(e.destination.url),n=this._normalizePathname(t.pathname);if(!this._isOwnPath(n))return;const r=this.isSameMatch(Go(n,this._basename)),i=r&&("push"===e.navigationType||"replace"===e.navigationType),s=t.search,o=this;e.intercept({handler:async()=>{try{await ol(o,o.outlet,n,o.path,s)}catch(e){throw console.error(`${Vs.router} applyRoute failed:`,e),e}},scroll:i?"manual":"after-transition",focusReset:r||null!==o.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const e=this._normalizePathname(window.location.pathname);this._isOwnPath(e)&&(await ol(this,this.outlet,e,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const e=hl();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const t=null!==document.querySelector("base[href]"),n=new URL(window.location.href);""!==this._basename||t||"/"===n.pathname||Ys(`${Vs.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||Ys(`${Vs.router} should have a <template> child element.`);const r=e?this._template.content.cloneNode(!0):null,i=await Wo(this),s=!e&&this._outlet.hasAttribute(so);if(s||this._outlet.rootNode.appendChild(i),null!==r){const e=this._template.content;for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(r)}0===this.routeChildNodes.length&&Ys(`${Vs.router} has no route definitions.`),e||this._ensureA11yRegion();const o=this._normalizePathname(window.location.pathname);if(e)return await this._renderForSsr(o),void(this._initialized=!0);if(s){if(await this._hydrateFromSsr(o))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(so);const e=this._outlet.rootNode;for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(i)}await ol(this,this.outlet,o,this._path,window.location.search||""),(s||null!==No())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(e){const t=this.outlet.rootNode,n=new Map;let r=!1;if(this._forEachRoute(e=>{n.has(e.absolutePath)?r=!0:n.set(e.absolutePath,e)}),r)return!1;if(null!==t.querySelector(Vs.layoutOutlet))return!1;const i=new Map,s=new Map,o=new Map,l=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT);let a=0;for(;l.nextNode();){const e=l.currentNode,t=e.data;if(a++,t.startsWith(lo)){const r=t.slice(15);if(i.has(r)||!n.has(r))return!1;i.set(r,e)}else if(t.startsWith(ao)){const r=t.slice(18);if(s.has(r)||!n.has(r))return!1;s.set(r,{comment:e,index:a})}else if(t.startsWith(uo)){const r=t.slice(16);if(o.has(r)||!n.has(r))return!1;o.set(r,{comment:e,index:a})}}if(s.size!==o.size)return!1;const u=[];for(const[e,t]of s){const n=o.get(e);if(!n)return!1;if(n.comment.parentNode!==t.comment.parentNode)return!1;if(n.index<=t.index)return!1;u.push({start:t.index,end:n.index})}for(const e of u)for(const t of u)if(e.start<t.start&&t.start<e.end&&e.end<t.end)return!1;const c=Go(e,this._basename);let h=Uo(this,c);if(!h){if(null===this._fallbackRoute)return!1;h={routes:[this._fallbackRoute],params:{},typedParams:{},path:c,lastPath:this._path}}if(h.lastPath=this._path,h.routes.length!==s.size)return!1;for(const e of h.routes)if(!s.has(e.absolutePath))return!1;const d=new Set;for(const e of this.routeChildNodes)d.add(e.absolutePath);for(const e of h.routes)for(const t of e.routeChildNodes)d.add(t.absolutePath);if(i.size!==d.size)return!1;for(const e of d)if(!i.has(e))return!1;for(const[e,t]of i){const r=n.get(e);t.parentNode.replaceChild(r.placeHolder,t)}for(const e of h.routes){const t=s.get(e.absolutePath).comment,n=o.get(e.absolutePath).comment,r=[],i=new Set;let l=t.nextSibling;for(;null!==l&&l!==n;){if(l.nodeType===Node.COMMENT_NODE){const e=l.data;if(e.startsWith(ao)){const t=e.slice(18);l=o.get(t).comment.nextSibling;continue}}if(i.has(l))l=l.nextSibling;else{if(l.nodeType===Node.ELEMENT_NODE&&l.tagName.toLowerCase()===Vs.link){const e=l.anchorElement;null!==e&&i.add(e)}r.push(l),l=l.nextSibling}}e.adoptChildNodes(r,n)}for(const{comment:e}of s.values())e.remove();this.outlet.removeAttribute(so);for(const e of h.routes)Xo(e,h);return this.outlet.lastRoutes=h.routes,!await sl(this,h)||(this.commitNavigation({params:h.params,typedParams:h.typedParams,routeName:h.routes[h.routes.length-1].name,data:h.data??null,search:window.location.search||"",path:c}),!0)}async _renderForSsr(e){const t=Go(e,this._basename),n=Uo(this,t),r=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===r.length&&Ys(`${Vs.router} No route matched for path: ${t}`),!r.some(e=>e.hasGuard)){await ol(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(e=>{e.placeHolder.data=`${lo}${e.absolutePath}`}),this.outlet.setAttribute(so,"");for(const e of this.outlet.lastRoutes)e.placeHolder.after(document.createComment(`${ao}${e.absolutePath}`))}}_offerInitialContentToBinder(){for(const e of this.outlet.lastRoutes)for(const t of e.childNodeArray)t.nodeType===Node.ELEMENT_NODE&&t.isConnected&&xo(t,To)}_forEachRoute(e,t=this){for(const n of t.routeChildNodes)e(n),this._forEachRoute(e,n)}async connectedCallback(){if(function(e){const t=e.constructor?.wcBindable,n=t?.inputs;if(void 0!==n)for(const t of n){const n=t.name;if(!Object.prototype.hasOwnProperty.call(e,n))continue;if(!cl(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),hl()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(e){throw this._rejectConnectedCallback?.(e),e}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(e){throw this._rejectConnectedCallback?.(e),e}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const e=ll();e&&!this._listeningNavigate&&(e.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),e||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(ll()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const pl=["title","rel","target","download","hreflang","lang","dir"];class ml extends HTMLElement{static get observedAttributes(){return["to",...pl]}_childNodeArray=[];_uuid=Xs();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const e=this.closest(Vs.router);if(e)return this._router=e;const t=this.getRootNode(),n=t.querySelector?.(Vs.router);if(n)return this._router=n;Ys(`${Vs.link} is not connected to a router.`)}_initialize(){this.style.display="none",this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(e){return Ko(e)}_joinInternalPath(e,t){const n=Vo(e),r=t.startsWith("/")?t:"/"+t,i=this._normalizePathname(r);return n?"/"===i?n+"/":n+i:i}_isInternalTarget(e){return e.startsWith("/")||e.startsWith("?")}_setAnchorHref(e,t){if(this._isInternalTarget(t)){const{pathname:n,search:r,hash:i}=al(t),s=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);e.href=s+ul(r)+i}else try{e.href=new URL(t).toString()}catch{Ys(`[${Vs.link}] Invalid URL in 'to' attribute: ${t}`)}}connectedCallback(){hl()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const e=this.nextElementSibling;return null!==e&&"A"===e.tagName&&e.hasAttribute(oo)?e:null}_connect(){this._initialized||this._initialize();const e=this.parentNode;if(!e)return;const t=this._findSsrAnchor();let n;if(null!==t)n=t,n.removeAttribute(oo),this._childNodeArray=Array.from(n.childNodes),this._setAnchorHref(n,this._path);else{const t=this.nextSibling;n=document.createElement("a"),this._setAnchorHref(n,this._path);for(const e of Array.from(this.attributes))(e.name.startsWith("aria-")||pl.includes(e.name))&&n.setAttribute(e.name,e.value);for(const e of this._childNodeArray)n.appendChild(e);t?e.insertBefore(n,t):e.appendChild(n)}if(this._anchorElement=n,hl())return this._updateActiveState(),void n.setAttribute(oo,"");ll()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!ll()?.navigate&&(this._onClick=async e=>{e.defaultPrevented||0===e.button&&(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||this._isInternalTarget(this._path)&&(e.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},n.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){ll()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const e=this._anchorElement;e&&(this._onClick&&(e.removeEventListener("click",this._onClick),this._onClick=void 0),e.remove(),this._anchorElement=null);for(const t of this._childNodeArray)e&&t.parentNode===e&&e.removeChild(t);this._router=null}attributeChangedCallback(e,t,n){if("to"===e&&t!==n)this._path=n||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(pl.includes(e)){const t=this._anchorElement;t&&(null===n?t.removeAttribute(e):t.setAttribute(e,n))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const e=this._normalizePathname(new URL(window.location.href).pathname),{pathname:t}=al(this._path),n=this._normalizePathname(this._isInternalTarget(this._path)?""===t?window.location.pathname:this._joinInternalPath(this.router.basename,t):t);this._anchorElement&&(e===n?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current","page")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const gl=[],yl=new Map;let bl=!1;const vl=new WeakMap;class wl extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super(),this.style.display="none"}_initialize(){if(!this._initialized){this._initialized=!0,this._childElementArray=Array.from(this.children);for(const e of this._childElementArray)this.removeChild(e)}}connectedCallback(){this._initialize(),bl||(this._captureInitialHead(),bl=!0),gl.push(this),this._reapplyHead()}disconnectedCallback(){const e=gl.indexOf(this);-1!==e&&gl.splice(e,1),this._reapplyHead()}get childElementArray(){return this._initialized||Ys("Head component is not initialized yet."),this._childElementArray}_getKey(e){const t=vl.get(e);if(void 0!==t)return t;const n=this._computeKey(e);return vl.set(e,n),n}_computeKey(e){const t=e.tagName.toLowerCase();if("title"===t)return"title";if("meta"===t)return`meta:${e.getAttribute("name")||""}:${e.getAttribute("property")||""}:${e.getAttribute("http-equiv")||""}:${e.hasAttribute("charset")?"charset":""}:${e.getAttribute("media")||""}`;if("link"===t)return`link:${e.getAttribute("rel")||""}:${e.getAttribute("href")||""}:${e.getAttribute("media")||""}:${e.getAttribute("hreflang")||""}`;if("base"===t)return"base";if("script"===t){const t=e.getAttribute("src")||"",n=e.getAttribute("id")||"",r=e.getAttribute("type")||"";return t||n?`script:${t}:${n}:${r}`:`script::${r}:${e.outerHTML.slice(0,100)}`}if("style"===t){const t=e.getAttribute("id")||"",n=e.getAttribute("media")||"";return t?`style:${t}:${n}`:`style::${n}:${e.outerHTML.slice(0,100)}`}return`${t}:${e.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const e=new Map;for(const t of Array.from(document.head.children)){const n=this._getKey(t);e.has(n)||e.set(n,t)}return e}_captureInitialHead(){const e=document.head;for(const t of Array.from(e.children)){const e=this._getKey(t);yl.has(e)||yl.set(e,t.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of gl)for(const n of t._childElementArray)e.add(this._getKey(n));for(const t of yl.keys())e.add(t);const t=this._buildHeadElementMap();for(const n of t.keys())e.add(n);for(const n of e){let e=null;for(let t=gl.length-1;t>=0;t--){const r=gl[t];for(const t of r._childElementArray)if(this._getKey(t)===n){e=t.cloneNode(!0);break}if(e)break}!e&&yl.has(n)&&(e=yl.get(n).cloneNode(!0));const r=t.get(n)??null;e?(r?r.replaceWith(e):document.head.appendChild(e),t.set(n,e),xo(e)||rl(e,`<${e.tagName.toLowerCase()}> inside <${Vs.head}>`,`<${Vs.head}> reflects its children into <head> with cloneNode, so the clone is not the node that was bound. Load @wcstack/state on this page, or write the value statically here.`)):(r?.remove(),t.delete(n))}}}await void function(e=customElements){e.get(Vs.layout)||e.define(Vs.layout,vo),e.get(Vs.layoutOutlet)||e.define(Vs.layoutOutlet,Mo),e.get(Vs.outlet)||e.define(Vs.outlet,wo),e.get(Vs.route)||e.define(Vs.route,co),e.get(Vs.router)||e.define(Vs.router,fl),e.get(Vs.link)||e.define(Vs.link,ml),e.get(Vs.head)||e.define(Vs.head,wl)}(void 0);const _l="data-fetchtarget",$l={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let kl=class{laneKey;policy;_ownerGeneration=0;_latestEpoch=0;_nextOperationId=1;_activeOperationId=void 0;_activeOperationIds=new Set;_queue=[];_inFlightCount=0;_terminal=new Map;_claimedOutcome=new Map;_controllers=new Map;_attempts=new Map;_withSignal;_trace;constructor(e,t,n={}){this.laneKey=e,this.policy=t,this._withSignal=n.withSignal??!1,this._trace=n.trace}get ownerGeneration(){return this._ownerGeneration}get inFlightCount(){return this._inFlightCount}get latestEpoch(){return this._latestEpoch}get activeOperationId(){return this._activeOperationId}begin(){let e;switch(this.policy){case"latest":e=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const t=this._nextOperationId++,n={operationId:t,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:e};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=t;break;case"queue":this._queue.push(n),void 0===this._activeOperationId&&(this._activeOperationId=t);break;case"overlap":this._activeOperationIds.add(t)}this._inFlightCount+=1,this._attempts.set(t,1);const r=this._makeAttempt(t,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:t,laneKey:this.laneKey,policy:this.policy}),{ticket:n,attempt:r}}retry(e){if(e.ownerGeneration!==this._ownerGeneration)return null;if(this._terminal.has(e.operationId))return null;const t=this._attempts.get(e.operationId);if(void 0===t)return null;const n=t+1;this._attempts.set(e.operationId,n),this._releaseController(e.operationId);const r=this._makeAttempt(e.operationId,n);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:e.operationId,laneKey:this.laneKey,attempt:n}),r}canCommit(e){if(e.ownerGeneration!==this._ownerGeneration)return!1;const t=this._terminal.get(e.operationId);return(void 0===t||"committing"===t)&&this._isEligible(e)}claimTerminal(e,t){return e.ownerGeneration===this._ownerGeneration&&!this._terminal.has(e.operationId)&&!!this._isEligible(e)&&(this._terminal.set(e.operationId,"committing"),this._claimedOutcome.set(e.operationId,t),!0)}claimedOutcome(e){return this._claimedOutcome.get(e.operationId)}finalize(e){const t=e.operationId,n=this._terminal.get(t);if(void 0!==n&&"committing"!==n)return;let r;r="committing"===n?this._claimedOutcome.get(t)??"stale":"stale",this._terminal.set(t,r),this._claimedOutcome.delete(t),this._releaseController(t),this._attempts.delete(t),this._inFlightCount>0&&(this._inFlightCount-=1),this._advanceBookkeeping(t),void 0!==this._trace&&("stale"===r?this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:t,laneKey:this.laneKey,outcome:r}))}signalOf(e){return this._controllers.get(e.operationId)?.signal}abort(e){this._abortController(e.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const e of this._activeOperationIds)this._abortController(e)}disposeOwner(){this._ownerGeneration+=1;for(const e of Array.from(this._controllers.keys()))this._abortController(e),this._releaseController(e);for(const e of Array.from(this._attempts.keys()))this._terminal.has(e)||this._terminal.set(e,"stale"),this._claimedOutcome.delete(e),this._attempts.delete(e),void 0!==this._trace&&this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey});this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0,this._inFlightCount=0}_makeAttempt(e,t){let n;if(this._withSignal&&"function"==typeof AbortController){const t=new AbortController;this._controllers.set(e,t),n=t.signal}return{operationId:e,attempt:t,signal:n}}_isEligible(e){switch(this.policy){case"latest":return e.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===e.operationId;case"overlap":return this._activeOperationIds.has(e.operationId)}}_advanceBookkeeping(e){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===e&&(this._activeOperationId=void 0);break;case"queue":{const t=this._queue.filter(t=>t.operationId!==e);this._queue.length=0,this._queue.push(...t),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(e)}}_abortController(e){const t=this._controllers.get(e);void 0===t||t.signal.aborted||t.abort()}_releaseController(e){this._controllers.delete(e)}};function Sl(e,t){return t.every(t=>"available"===e.availability.get(t))}const Nl=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let Al=class e extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",semantics:"state",getter:e=>e.detail.value},{name:"loading",event:"wcs-fetch:loading-changed",semantics:"state"},{name:"error",event:"wcs-fetch:error",semantics:"state"},{name:"status",event:"wcs-fetch:response",semantics:"state",getter:e=>e.detail.status},{name:"objectURL",event:"wcs-fetch:response",semantics:"state",getter:e=>e.detail.objectURL},{name:"errorInfo",event:"wcs-fetch:error-info-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"}],commands:[{name:"fetch",async:!0},{name:"abort"}]};_target;_value=null;_loading=!1;_error=null;_status=0;_objectURL=null;_promise=Promise.resolve(null);_lane=new kl("fetch","latest",{withSignal:!0});_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(e){super(),this._target=e??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._lane.disposeOwner(),null!==this._objectURL&&(this._revokeObjectURL(this._objectURL),this._objectURL=null)}get value(){return this._value}get loading(){return this._loading}get error(){return this._error}get status(){return this._status}get objectURL(){return this._objectURL}get promise(){return this._promise}get errorInfo(){return this._errorInfo}get supported(){return Sl(this.platformAssessment,e.REQUIRED_CAPABILITIES)}get platformAssessment(){return function(e,t){const n=new Map,r=t=>{const n=e.get(t);return void 0===n?"unknown":n.probe()?"available":"missing"};let i=!0;for(const e of t.required){const t=r(e);n.set(e,t),"available"!==t&&(i=!1)}let s=!0;for(const e of t.optional??[]){const t=r(e);n.set(e,t),"available"!==t&&(s=!1)}const o=i?s?"ready":"degraded":"idle",l=[...t.required,...t.optional??[]],a=l.some(t=>!0===e.get(t)?.requiresSecureContext),u=l.some(t=>!0===e.get(t)?.requiresUserActivation),c=a?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",h=u?"required":"not-applicable";return{availability:n,permission:t.permission??"not-applicable",readiness:o,activity:t.activity??"inactive",preconditions:{secureContext:c,userActivation:h},epoch:t.epoch??0,lastError:t.lastError}}(Nl,{required:e.REQUIRED_CAPABILITIES,optional:e.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(e,t,n,r,i){this._commitErrorInfo({code:e,phase:t,recoverable:n,message:r,...void 0===i?{}:{capabilityId:i}})}_commitErrorInfo(e){this._errorInfo!==e&&(this._errorInfo=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:e,bubbles:!0})))}_setLoading(e){this._loading=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:e,bubbles:!0}))}_setError(e){this._error!==e&&(this._error=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:e,bubbles:!0})))}_setResponse(e,t,n=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=n,this._value=e,this._status=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:e,status:t,objectURL:n},bubbles:!0}))}_createObjectURL(e){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(e):null}_revokeObjectURL(e){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(e)}abort(){this._lane.abortActive()}_commitStep(e,t){this._lane.canCommit(e)&&t()}async fetch(t,n={}){if(!t)return this._setErrorInfo("invalid-argument","start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const r=this.platformAssessment;if(!Sl(r,e.REQUIRED_CAPABILITIES)){const t=e.REQUIRED_CAPABILITIES.find(e=>"available"!==r.availability.get(e));return this._setErrorInfo("capability-missing","start",!1,`Required capability "${t}" is unavailable.`,t),this._setError({message:`Required capability "${t}" is unavailable.`}),null}const i=this._doFetch(t,n);return this._promise=i,i}async _doFetch(e,t){const n=this._lane.begin(),{ticket:r,attempt:i}=n,s=i.signal;this._commitStep(r,()=>this._setLoading(!0)),this._commitStep(r,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:o="GET",body:l=null,contentType:a=null,forceText:u=!1,responseType:c="auto",timeout:h=0}=t;let d=null;h>0&&(d=setTimeout(()=>{if(!this._lane.claimTerminal(r,"timeout"))return;const e=`Request timed out after ${h}ms.`;this._commitStep(r,()=>{this._setErrorInfo("timeout","execute",!0,e),this._setError({name:"TimeoutError",message:e})}),this._commitStep(r,()=>this._setResponse(null,0)),this._commitStep(r,()=>this._setLoading(!1)),this._lane.abort(r),this._lane.finalize(r)},h));const f={...t.headers??{}};try{a&&!f["Content-Type"]&&(f["Content-Type"]=a);const t={method:o,headers:f,signal:s};"GET"!==o&&"HEAD"!==o&&null!==l&&(t.body=l);const n=await globalThis.fetch(e,t);let i=null;if("HEAD"===o);else if(n.ok)if(u)i=await n.text();else if("blob"===c)i=await n.blob();else if("arrayBuffer"===c)i=await n.arrayBuffer();else if("text"===c)i=await n.text();else if("json"===c)i=await n.json();else{const e=n.headers.get("Content-Type")||"";i=e.includes("application/json")?await n.json():await n.text()}if(!n.ok){const e=await n.text().catch(()=>""),t={status:n.status,statusText:n.statusText,body:e};return this._lane.claimTerminal(r,"error")?(this._commitStep(r,()=>{this._setErrorInfo("http-error","execute",!0,`HTTP ${n.status} ${n.statusText}`),this._setError(t)}),this._commitStep(r,()=>this._setResponse(null,n.status)),this._commitStep(r,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(r,"success"))return null;const h=i instanceof Blob?this._createObjectURL(i):null;return this._commitStep(r,()=>this._setResponse(i,n.status,h)),this._commitStep(r,()=>this._setLoading(!1)),this._value}catch(e){return e&&"AbortError"===e.name?(this._lane.claimTerminal(r,"aborted")&&this._commitStep(r,()=>this._setLoading(!1)),null):this._lane.claimTerminal(r,"error")?(this._commitStep(r,()=>{const t=String(e?.message??"Network request failed.");this._setErrorInfo("network","execute",!0,t),this._setError(e??{message:t})}),this._commitStep(r,()=>this._setResponse(null,0)),this._commitStep(r,()=>this._setLoading(!1)),null):null}finally{null!==d&&clearTimeout(d),this._lane.finalize(r)}}},El=!1;function Cl(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest(`[${_l}]`);if(!n)return;const r=n.getAttribute(_l);if(!r)return;const i=customElements.get($l.fetch),s=document.getElementById(r);if(!(i&&s instanceof i))return;const o=s;o.url&&(e.preventDefault(),o.fetch())}function xl(e,t){let n=Object.getPrototypeOf(e);for(;null!==n;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return"function"==typeof e.get||"function"==typeof e.set;n=Object.getPrototypeOf(n)}return!1}const Tl=Symbol.for("wcstack.trustedTypes.policy");function Pl(){const e=globalThis[Tl];return null===e||"object"!=typeof e?null:e}let Ol,Ml=!1;let Ll=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Al.wcBindable,properties:[...Al.wcBindable.properties,{name:"trigger",event:"wcs-fetch:trigger-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"},{name:"target"},{name:"manual"},{name:"body"},{name:"responseType"},{name:"trigger"}]};static get observedAttributes(){return["url"]}_core;_body=null;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_autoPending=!1;_connectResolve=null;_lastFetchedUrl=null;_internals=null;constructor(){super(),this._internals=this._initInternals(),this._wireStates({"wcs-fetch:loading-changed":e=>({loading:!0===e}),"wcs-fetch:error":e=>({error:null!=e})}),this._core=new Al(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const e=this.attachInternals();return e.states.add("wcs-probe"),e.states.delete("wcs-probe"),e}catch{return null}}_wireStates(e){if(null===this._internals)return;const t=this._internals.states;for(const[n,r]of Object.entries(e))this.addEventListener(n,e=>{const n=this.hasAttribute("debug-states");for(const[i,s]of Object.entries(r(e.detail))){try{s?t.add(i):t.delete(i)}catch{}n&&this.toggleAttribute(`data-wcs-state-${i}`,s)}})}get url(){return this.getAttribute("url")||""}set url(e){null==e?this.removeAttribute("url"):this.setAttribute("url",e)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(e){null==e?this.removeAttribute("method"):this.setAttribute("method",e)}get target(){return this.getAttribute("target")}set target(e){null==e?this.removeAttribute("target"):this.setAttribute("target",e)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(e){null==e?this.removeAttribute("response-type"):this.setAttribute("response-type",e)}get value(){return this._core.value}get loading(){return this._core.loading}get error(){return this._core.error}get status(){return this._core.status}get objectURL(){return this._core.objectURL}get errorInfo(){return this._core.errorInfo}get promise(){return this._core.promise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(e){e?this.setAttribute("manual",""):this.removeAttribute("manual")}get body(){return this._body}set body(e){this._body=e??null}get trigger(){return this._trigger}set trigger(e){if(e){if(!this.url)return;this._trigger=!0,this.fetch().finally(()=>{this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-fetch:trigger-changed",{detail:!1,bubbles:!0}))})}}_collectHeaders(){const e={},t=this.querySelectorAll($l.fetchHeader);for(const n of t){const t=n.headerName,r=n.headerValue;t&&(e[t]=r)}return e}_isNativeBodyInit(e){return e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||e instanceof ArrayBuffer||ArrayBuffer.isView(e)}_collectBody(e){if(null!==e)return"string"==typeof e||this._isNativeBodyInit(e)?{body:e,contentType:null}:{body:JSON.stringify(e),contentType:"application/json"};const t=this.querySelector($l.fetchBody);return t?{body:t.bodyContent||null,contentType:t.contentType}:{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const e=this._connectResolve;this._connectResolve=null;const t=this.url;this.isConnected&&!this.manual&&t&&t!==this._lastFetchedUrl?this.fetch().finally(()=>e?.()):e?.()}))}async fetch(){this._lastFetchedUrl=this.url;const e=this._collectHeaders(),t=this._body;this._body=null;const{body:n,contentType:r}=this._collectBody(t);n instanceof FormData&&Object.keys(e).some(e=>"content-type"===e.toLowerCase())&&console.warn("[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. This drops the multipart boundary the browser adds automatically; remove the Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.");const i=await this._core.fetch(this.url,{method:this.method,headers:e,body:n,contentType:r,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==i){const e=document.getElementById(this.target);e&&function(e,t){try{e.innerHTML=function(e){if("string"!=typeof e)return e;const t=Pl(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(t)}catch(e){if(function(){if(void 0!==Ol)return Ol;if(!("trustedTypes"in globalThis))return Ol=!1,Ol;try{document.createElement("div").innerHTML="<i></i>",Ol=!1}catch{Ol=!0}return Ol}())return void function(){if(Ml)return;Ml=!0;const e="function"==typeof Pl()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/fetch deliberately does not pass responses through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/fetch] The "target" HTML replace mode was blocked by Trusted Types (require-trusted-types-for 'script'). ${e}\nInstall a sanitizing policy before the first fetch:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr drop "target" and bind the response through @wcstack/state. See docs/csp.md section 7.`)}();throw e}}(e,i)}return i}attributeChangedCallback(e,t,n){"url"===e&&this._scheduleAutoFetch()}connectedCallback(){!function(e){const t=e.constructor?.wcBindable,n=t?.inputs;if(void 0!==n)for(const t of n){const n=t.name;if(!Object.prototype.hasOwnProperty.call(e,n))continue;if(!xl(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this.style.display="none",El||(El=!0,document.addEventListener("click",Cl)),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(e=>{this._connectResolve=e})),this._scheduleAutoFetch()}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}};class Il extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class jl extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}let Rl=class extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;get target(){return this.getAttribute("target")||""}set target(e){this.setAttribute("target",e)}get root(){return this.getAttribute("root")}set root(e){null===e?this.removeAttribute("root"):this.setAttribute("root",e)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(e){this.setAttribute("root-margin",e)}get threshold(){const e=Number(this.getAttribute("threshold")??"0");return Number.isFinite(e)?e:0}set threshold(e){this.setAttribute("threshold",String(e))}get disabled(){return this.hasAttribute("disabled")}set disabled(e){e?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(e){e?this.setAttribute("once",""):this.removeAttribute("once")}connectedCallback(){this._observe()}disconnectedCallback(){this._disconnectObserver()}attributeChangedCallback(){this.isConnected&&this._observe()}_observe(){this._disconnectObserver(),this._done||this.disabled||!this.target||"undefined"==typeof IntersectionObserver||(this._observer=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&this._triggerFetch()},{root:this._resolveRoot(),rootMargin:this.rootMargin,threshold:this.threshold}),this._observer.observe(this))}_disconnectObserver(){this._observer&&(this._observer.disconnect(),this._observer=null)}_resolveRoot(){return this.root&&document.getElementById(this.root)||null}_triggerFetch(){const e=document.getElementById(this.target);e instanceof Ll&&(e.loading||(e.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(e=customElements){e.get($l.fetch)||e.define($l.fetch,Ll),e.get($l.fetchHeader)||e.define($l.fetchHeader,Il),e.get($l.fetchBody)||e.define($l.fetchBody,jl),e.get($l.infiniteScroll)||e.define($l.infiniteScroll,Rl)}(void 0);const Hl="data-storagetarget",Wl={storage:"wcs-storage"},zl="wcs-storage:value-changed",Dl="wcs-storage:loading-changed",Ul="wcs-storage:error",Fl="wcs-storage:error-info-changed",ql="wcs-storage:trigger-changed";let Bl=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:zl,semantics:"state",getter:e=>e.detail},{name:"loading",event:Dl,semantics:"state"},{name:"error",event:Ul,semantics:"state"},{name:"errorInfo",event:Fl,semantics:"state"}],inputs:[{name:"key"},{name:"type"}],commands:[{name:"load"},{name:"save"},{name:"remove"}]};_target;_value=null;_loading=!1;_error=null;_errorInfo=null;_key="";_type="local";_storageListener=null;_gen=0;_ready=Promise.resolve();constructor(e){super(),this._target=e??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stopSync()}get value(){return this._value}set value(e){Object.is(e,this._value)||this._setValue(e)}get loading(){return this._loading}get error(){return this._error}get errorInfo(){return this._errorInfo}get key(){return this._key}set key(e){this._key=String(e)}get type(){return this._type}set type(e){"local"===e||"session"===e?this._type=e:this._setError({operation:"type",message:`Invalid storage type: "${e}". Must be "local" or "session".`})}_getStorage(){return"session"===this._type?sessionStorage:localStorage}_setLoading(e){this._loading=e,this._target.dispatchEvent(new CustomEvent(Dl,{detail:e,bubbles:!0}))}_setError(e,t){this._error!==e&&(this._error=e,this._commitErrorInfo(null===e?null:function(e,t){return void 0===t?{code:"invalid-argument",phase:"start",recoverable:!1,message:e.message}:"QuotaExceededError"===t?{code:"quota-exceeded",phase:"execute",recoverable:!0,message:e.message}:"SecurityError"===t?{code:"not-allowed",phase:"execute",recoverable:!1,message:e.message}:{code:"storage-error",phase:"execute",recoverable:!0,message:e.message}}(e,t)),this._target.dispatchEvent(new CustomEvent(Ul,{detail:e,bubbles:!0})))}_commitErrorInfo(e){this._errorInfo=e,this._target.dispatchEvent(new CustomEvent(Fl,{detail:e,bubbles:!0}))}_toStorageError(e,t){return{operation:e,message:t instanceof Error?t.message:String(t)}}_errName(e){return e instanceof Error?e.name:""}_setValue(e){this._value=e,this._target.dispatchEvent(new CustomEvent(zl,{detail:e,bubbles:!0}))}load(){if(!this._key)return this._setError({operation:"load",message:"key is required."}),null;this._setLoading(!0),this._setError(null);try{const e=this._getStorage().getItem(this._key);if(null===e)this._setValue(null);else try{this._setValue(JSON.parse(e))}catch{this._setValue(e)}return this._setLoading(!1),this._value}catch(e){return this._setError(this._toStorageError("load",e),this._errName(e)),this._setLoading(!1),null}}save(e){if(this._key){this._setLoading(!0),this._setError(null);try{const t=this._getStorage();null==e?(t.removeItem(this._key),this._setValue(null)):"string"==typeof e?(t.setItem(this._key,e),this._setValue(e)):(t.setItem(this._key,JSON.stringify(e)),this._setValue(e)),this._setLoading(!1)}catch(e){this._setError(this._toStorageError("save",e),this._errName(e)),this._setLoading(!1)}}else this._setError({operation:"save",message:"key is required."})}remove(){if(this._key){this._setLoading(!0),this._setError(null);try{this._getStorage().removeItem(this._key),this._setValue(null),this._setLoading(!1)}catch(e){this._setError(this._toStorageError("remove",e),this._errName(e)),this._setLoading(!1)}}else this._setError({operation:"remove",message:"key is required."})}startSync(){if(this._storageListener)return;const e=++this._gen;this._storageListener=t=>{if(e===this._gen&&t.key===this._key&&"session"!==this._type)if(this._setError(null),null===t.newValue)this._setValue(null);else try{this._setValue(JSON.parse(t.newValue))}catch{this._setValue(t.newValue)}},globalThis.addEventListener("storage",this._storageListener)}stopSync(){this._storageListener&&(globalThis.removeEventListener("storage",this._storageListener),this._storageListener=null)}},Kl=!1;function Gl(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest(`[${Hl}]`);if(!n)return;const r=n.getAttribute(Hl);if(!r)return;const i=customElements.get(Wl.storage),s=document.getElementById(r);i&&s instanceof i&&(e.preventDefault(),s.save())}function Vl(e,t){let n=Object.getPrototypeOf(e);for(;null!==n;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return"function"==typeof e.get||"function"==typeof e.set;n=Object.getPrototypeOf(n)}return!1}let Jl=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Bl.wcBindable,properties:[...Bl.wcBindable.properties,{name:"trigger",event:ql,semantics:"state"}],inputs:[{name:"key"},{name:"type"},{name:"value"},{name:"manual"},{name:"trigger"}]};static get observedAttributes(){return["key","type"]}_core;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_internals=null;constructor(){super(),this._core=new Bl(this),this._internals=this._initInternals(),this._wireStates({[Dl]:e=>({loading:!0===e}),[Ul]:e=>({error:null!=e})})}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const e=this.attachInternals();return e.states.add("wcs-probe"),e.states.delete("wcs-probe"),e}catch{return null}}_wireStates(e){if(null===this._internals)return;const t=this._internals.states;for(const[n,r]of Object.entries(e))this.addEventListener(n,e=>{const n=this.hasAttribute("debug-states");for(const[i,s]of Object.entries(r(e.detail))){try{s?t.add(i):t.delete(i)}catch{}n&&this.toggleAttribute(`data-wcs-state-${i}`,s)}})}_syncCore(){this._core.key=this.key,this._core.type=this.type}get key(){return this.getAttribute("key")||""}set key(e){this.setAttribute("key",e)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(e){this.setAttribute("type",e)}get value(){return this._core.value}set value(e){this.manual?this._core.value=e:(this._syncCore(),this._core.save(e))}get loading(){return this._core.loading}get error(){return this._core.error}get errorInfo(){return this._core.errorInfo}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(e){e?this.setAttribute("manual",""):this.removeAttribute("manual")}get trigger(){return this._trigger}set trigger(e){if(e){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(ql,{detail:!1,bubbles:!0}))}}}load(){return this._syncCore(),this._core.load()}save(){this._syncCore(),this._core.save(this._core.value)}remove(){this._syncCore(),this._core.remove()}attributeChangedCallback(e,t,n){this.isConnected&&("key"===e&&(this._syncCore(),n&&!this.manual&&this.load()),"type"===e&&this._syncCore())}connectedCallback(){!function(e){const t=e.constructor?.wcBindable,n=t?.inputs;if(void 0!==n)for(const t of n){const n=t.name;if(!Object.prototype.hasOwnProperty.call(e,n))continue;if(!Vl(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this.style.display="none",Kl||(Kl=!0,document.addEventListener("click",Gl)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(e=customElements){e.get(Wl.storage)||e.define(Wl.storage,Jl)}(void 0);const Ql="*",Xl="vanilla",Yl={loaders:{[Xl]:{postfix:".js",loader:async function(e){return(await(import(`${e}`))).default}},[Ql]:Xl},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function Zl(e){if(e.startsWith("@components/")){if(e.endsWith("/")){const t=e.slice(12,e.length-1),[n,r]=t.split("|",2);if(""===n)throw new Error("Invalid importmap key: "+e);return{key:e,prefix:n.replaceAll("/","-").toLowerCase(),loaderKey:r??null,isNameSpaced:!0}}{const t=e.slice(12),[n,r]=t.split("|",2),[i,s]=(r??"").split(",",2);if(""===n)throw new Error("Invalid importmap key: "+e);return{key:e,tagName:n.replaceAll("/","-").toLowerCase(),loaderKey:i||null,extends:s||null,isNameSpaced:!1}}}return null}function ea(e,t,n){let r;if(null===t||t===Ql||""===t){let t=null;const i=[];for(const[e,t]of Object.entries(n)){if(e===Ql)continue;const r="string"==typeof t?n[t]:t;"string"!=typeof r&&i.push(r)}i.sort((e,t)=>t.postfix.length-e.postfix.length);for(const n of i)if(e.endsWith(n.postfix)){t=n;break}t?r=t:(r=n[Ql],"string"==typeof r&&(r=n[r]))}else if(r=n[t],!r)throw new Error("Loader not found: "+t);if("string"==typeof r)throw new Error("Loader redirection is not supported here");return r}const ta=new Set,na=new Map;let ra=new WeakMap;function ia(e){if(e===globalThis.customElements)return na;let t=ra.get(e);return void 0===t&&(t=new Map,ra.set(e,t)),t}const sa=new Map;async function oa(e,t,n){try{if(customElements.get(t))return;const r=await n.loader(e.key);if(null!==r){let n=e.extends;if(null===n&&(n=function(e){for(const[t,n]of sa)if(e.prototype instanceof t)return n;return null}(r)),customElements.get(t))return;null===n?customElements.define(t,r):customElements.define(t,r,{extends:n})}}catch(e){ta.has(t)||(console.error(`Failed to eager load component '${t}':`,e),ta.add(t))}}function la(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined||"function"!=typeof t.define?null:t}function aa(e){const t=e.tagName.toLowerCase();let n,r;if(t.includes("-"))n=t,r=null;else{const i=e.getAttribute("is");if(null===i)throw new Error("Custom element without a dash or 'is' attribute found: "+t);if(!i.includes("-"))throw new Error("Custom element 'is' attribute without a dash found: "+t);n=i,r=t}return{name:n,extends:r}}"undefined"!=typeof window&&[[HTMLButtonElement,"button"],[HTMLInputElement,"input"],[HTMLAnchorElement,"a"],[HTMLImageElement,"img"],[HTMLDivElement,"div"],[HTMLSpanElement,"span"],[HTMLParagraphElement,"p"],[HTMLUListElement,"ul"],[HTMLOListElement,"ol"],[HTMLLIElement,"li"],[HTMLTableElement,"table"],[HTMLFormElement,"form"],[HTMLLabelElement,"label"],[HTMLSelectElement,"select"],[HTMLTextAreaElement,"textarea"],[HTMLHeadingElement,"h1"],[HTMLQuoteElement,"blockquote"],[HTMLPreElement,"pre"],[HTMLBRElement,"br"],[HTMLHRElement,"hr"],[HTMLModElement,"ins"],[HTMLTableCaptionElement,"caption"],[HTMLTableColElement,"col"],[HTMLTableSectionElement,"tbody"],[HTMLTableRowElement,"tr"],[HTMLTableCellElement,"td"],[HTMLFieldSetElement,"fieldset"],[HTMLLegendElement,"legend"],[HTMLDListElement,"dl"],[HTMLOptGroupElement,"optgroup"],[HTMLOptionElement,"option"],[HTMLStyleElement,"style"],[HTMLScriptElement,"script"],[HTMLTemplateElement,"template"],[HTMLCanvasElement,"canvas"],[HTMLIFrameElement,"iframe"],[HTMLObjectElement,"object"],[HTMLEmbedElement,"embed"],[HTMLVideoElement,"video"],[HTMLAudioElement,"audio"],[HTMLTrackElement,"track"],[HTMLMapElement,"map"],[HTMLAreaElement,"area"],[HTMLSourceElement,"source"],[HTMLParamElement,"param"],[HTMLMeterElement,"meter"],[HTMLProgressElement,"progress"],[HTMLOutputElement,"output"],[HTMLDetailsElement,"details"],[HTMLDialogElement,"dialog"],[HTMLMenuElement,"menu"],[HTMLSlotElement,"slot"],[HTMLTimeElement,"time"],[HTMLDataElement,"data"],[HTMLPictureElement,"picture"]].forEach(([e,t])=>{void 0!==e&&sa.set(e,t)});const ua=new WeakSet,ca=new WeakSet;async function ha(e,t,n){e.shadowRoot&&(ua.has(e)||await async function(e,t,n){ua.add(e),await ma(e.shadowRoot,t,n)}(e,t,n))}async function da(e,t,n,r){const i=function(e,t){for(const[n,r]of Object.entries(t))if(e.startsWith(n+"-"))return r;return null}(e.name,n);if(null===i)throw new Error("No matching namespace found for lazy loaded component: "+e.name);const s=ia(r),o=s.get(e.name);if(void 0!==o)return void await o;const l=async function(e,t,n,r){try{let i;try{i=ea("",n.loaderKey,t.loaders)}catch(t){throw new Error("Loader redirection is not supported for lazy loaded components: "+e.name)}const s=e.name.slice(n.prefix.length+1);if(""===s)throw new Error("Invalid component name for lazy loaded component: "+e.name);const o=n.key+s+i.postfix;if(r.get(e.name))return;const l=await i.loader(o);if(null===l)throw new Error("Loader returned null for component: "+e.name);if(r.get(e.name))return;null===e.extends?r.define(e.name,l):r.define(e.name,l,{extends:e.extends})}catch(t){console.error(`Failed to lazy load component '${e.name}':`,t),ta.add(e.name)}}(e,t,i,r);s.set(e.name,l);try{await l}finally{s.delete(e.name)}}async function fa(e,t,n,r){const i=[],s=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_ELEMENT,e=>(e=>(e instanceof Element&&(e.tagName.includes("-")||e.getAttribute("is")?.includes("-")))??!1)(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP);for(;s.nextNode();)i.push(s.currentNode);const o=[],l=new Set;for(const e of i){const i=aa(e);void 0===r.get(i.name)?(ca.has(e)||(ca.add(e),r.whenDefined(i.name).then(async()=>{await ha(e,t,n)})),l.has(i.name)||ta.has(i.name)||(l.add(i.name),o.push(i))):await ha(e,t,n)}let a=0;for(const e of o)await da(e,t,n,r),a++;return a}async function pa(e,t,n,r){for(;await fa(e,t,n,r)>0;);}async function ma(e,t,n){if(0===Object.keys(n).length)return null;const r=function(e=null){if(null!=e){const t=e.customElementRegistry;if(null===t)return null;if(void 0!==t)return la(t)}return la(globalThis.customElements)}(e);if(null===r)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await pa(e,t,n,r)}catch(e){throw new Error("Failed to lazy load components: "+e)}if(!t.observable)return null;const i=new MutationObserver(async()=>{try{await pa(e,t,n,r)}catch(e){console.error("Failed to lazy load components: "+e)}});return i.observe(e,{childList:!0,subtree:!0}),i}class ga extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),ga._instance)throw new Error(`${Yl.tagNames.autoloader} can only be instantiated once.`);ga._instance=this;const e=function(){const e={imports:{}};return document.querySelectorAll('script[type="importmap"]').forEach(t=>{try{const n=JSON.parse(t.innerHTML);n.imports&&(e.imports=Object.assign(e.imports,n.imports))}catch(e){throw new Error("Failed to parse importmap JSON: "+e)}}),Object.keys(e.imports).length>0?e:null}();if(e){const{prefixMap:t,loadMap:n}=function(e){const t={},n={};for(const[r,i]of Object.entries(e.imports)){const e=Zl(r);null!==e&&(e.isNameSpaced?t[e.prefix]=e:n[e.tagName]=e)}return{prefixMap:t,loadMap:n}}(e);this._prefixMap=t,async function(e,t){const n=[];for(const[r,i]of Object.entries(e)){let s;try{s=ea(i.key,i.loaderKey,t)}catch(e){throw new Error("Loader redirection is not supported for eager loaded components: "+r)}n.push(oa(i,r,s))}await Promise.all(n)}(n,Yl.loaders).catch(e=>{console.error("Failed to eager load components:",e)})}}async connectedCallback(){this._initialized||(this._initialized=!0,this._prefixMap&&("loading"===document.readyState&&await new Promise(e=>document.addEventListener("DOMContentLoaded",()=>e(),{once:!0})),this._observer=await ma(document,Yl,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,ga._instance===this&&(ga._instance=null)}}!function(e=customElements){e.get(Yl.tagNames.autoloader)||e.define(Yl.tagNames.autoloader,ga)}(void 0);
|
|
1
|
+
var e=class{constructor(e,n,r){this.h=[],this.getter=null,this.oe=null,this.de=!1,this.G=[],this.$e=[],this.ut=null,this.F=-1,this.J=t,this.Fe=null,this.Tt=null,this.At=null,this.q=null,this.Ft=new Set,this.t=e,this.d=r,this.s=n;let i=null===r?[null]:r.f.slice(),s="*"===n;s&&i.push(r),this.n=i.length-1,this.U=s?[]:null===r?[n]:[...r.U,n],this.f=i}jn(e){this.Ft.has(e)||(this.Ft.add(e),this.G.push(e),e.$e.push(this))}Po(){this.getter=null,this.oe=null,this.F=-1,this.J=t,this.G.length=0,this.Ft.clear(),this.$e.length=0,this.ut=null,this.Fe=null,this.Tt=null,this.At=null,this.q=null}Q(e){let t=this;for(;null!==t;){if(t===e)return!0;t=t.d}return!1}},t=Symbol("unset"),n=Symbol("dirty"),r=Symbol("failed"),i=class{constructor(e=null){this.Ot=new Map,this.Ln=e}Ct(e){return this.Ot.get(e)}get(t){let n=this.Ot.get(t);if(void 0!==n)return n;let r=t.lastIndexOf("."),i=r<0?null:this.get(t.slice(0,r));return n=new e(t,t.slice(r+1),i),this.Ln?.(n),this.Ot.set(t,n),i&&i.h.push(n),n}all(){return this.Ot.values()}},s=new Map;function o(e){let t=s.get(e);if(void 0!==t)return t;let n=!0,r=e.split("."),i=[];for(let e=0;e<r.length;e++){let t=r[e],s=t.charCodeAt(0);e>0&&s>=48&&s<=57?(n=!1,i.push(Number(t)),r[e]="*"):"*"===t&&i.push(-1)}if(!n)return{o:r.join("."),indexes:i};let o={o:e,indexes:null};return s.set(e,o),o}var l=class{constructor(e,t,n){this.dt=null,this.$=null,this.fe=null,this.q=null,this.h=null,this.y=!0,this.l=e,this.b=t,this.T=n}},a=class{constructor(e,t){this.C=null,this.u=[],this.$=null,this.L=null,this.Z=!1,this.It=!1,this.ft=!1,this.o=e,this.re=t,this.n=e.n+1}},u=[],c={};function h(e,t){return null==e?t:(...n)=>{e(...n),t(...n)}}function d(e,t,n){return null==t?n:(...r)=>{let i=t(...r);return e(i)?i:n(...r)}}var f=e=>!0===e,p=e=>void 0!==e,m=e=>null!=e,g=new Set;function y(e){let t=e.$features;if(null!=c.Lt&&Array.isArray(t)){let e=t.filter(e=>!g.has(e));if(e.length>0)return c.Lt(e)}}function b(e,t){if(!g.has(e))throw new Error(`[@wcstack/state] [wcs/feature-not-installed] ${t} needs the add-on @wcstack/state/features/${e}`)}function v(e,t,n){throw new Error(`[@wcstack/state] ${e}${c.Ao?.(e,t,n)??""}`)}function w(e,t=[]){return c.Fo?.(e,t)??`#${e}${t.map(e=>` ${"string"==typeof e?JSON.stringify(e):String(e)}`).join("")}`}function _(e,t,n,r){v(w(e,t),n,r)}var $=class{constructor(e){this.pt=new Set,this.name=e}get size(){return this.pt.size}subscribe(e){return this.pt.add(e),()=>{this.pt.delete(e)}}unsubscribe(e){return this.pt.delete(e)}emit(...e){let t=[];for(let n of this.pt)try{t.push(n(...e))}catch(e){t.push(void 0),console.error(`[@wcstack/state] ${w(17,[this.name])}`,e)}return t}};function k(e,t,n){if(void 0===e)return[];Array.isArray(e)||_(18,[t]);let r=new Set;for(let i of e)("string"!=typeof i||""===i)&&_(19,[t]),i===n&&_(20,[t,i,n]),r.has(i)&&_(21,[t,i]),r.add(i);return e}var S=Symbol.for("wcstack.transition-runner");function N(e){let t=globalThis[S];return null==t||"wcs-transition-runner"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.run||"function"!=typeof t.accepts||!t.accepts(e)?null:t}function E(e,t,n){let r=N(e);if(null!==r)return r.run(t,{source:e,types:n});t()}var A="else",C="eventToken",x=/^\$[1-9]\d{0,2}$/,T=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function P(e){let t=[],n=[],r="",i=null,s=!1,o=-1,l=-1,a=e=>{let i=function(e,t,n){let r=-1===t?e.length:t,i=-1===n?0:n;return e.slice(r-e.slice(0,r).trimStart().length,i+e.slice(i).trimEnd().length)}(r,o,l);(!e||i||s)&&(t.push(i),n.push(function(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:T.test(e)?Number(e):e)}(i,s))),r="",s=!1,o=-1,l=-1};for(let t=0;t<e.length;t++){let n=e[t];i?n===i?i=null:(-1===o&&(o=r.length),r+=n,l=r.length):'"'===n||"'"===n?(i=n,s=!0):","===n?a():r+=n}return null!==i&&_(107,[i,e]),a(!0),{args:t,literals:n}}var O=e=>e.trim();function L(e,t){let n=[],r=null;for(let i=0;i<e.length;i++){let s=e[i];null!==r?s===r&&(r=null):"'"===s||'"'===s?r=s:s===t&&n.push(i)}return n}var M=(e,t)=>L(e,t)[0]??-1;function I(e,t){let n=[],r=0;for(let i of L(e,t))n.push(e.slice(r,i)),r=i+1;return n.push(e.slice(r)),n}function j(e,t,n){let r=M(e,"|");if(-1===r)return[e.trim(),[]];let i=e.slice(r+1).trim(),s=n.get(i);return void 0===s&&(s=function(e,t,n){let r=n??e.join("|");return e.map(e=>{let n=M(e,"("),i=(e=>L(e,")").pop()??-1)(e);if(-1===i&&(i=e.lastIndexOf(")")),-1!==n&&-1===i&&_(108,[e]),-1!==i&&-1===n&&_(109,[e]),-1!==i&&i<n&&_(110,[e]),-1!==i&&e.slice(i+1).trim().length>0){let t=e.slice(i+1).trim();_(111,[e,t])}let s=(-1===n?e:e.substring(0,n)).trim();if(0===s.length&&_(112,[r]),s.includes("#")){let[,e]=s.split("#");_("input"===t?113:114,[s,e])}return-1===n?{Bn:s,args:[],literals:[]}:{Bn:s,...P(e.substring(n+1,i))}})}(I(i,"|").map(O),t,e),n.set(i,s)),[e.slice(0,r).trim(),s]}var R=new Map;function H(e){_(1101,[e])}function W(e){let[t,n]=j(e,"output",R);t.includes("@")&&_(32,[t]);let r=t,i=r.startsWith("."),s=i?r.slice(1):r;return(s.length>0&&s.split(".").some(e=>0===e.length)||!i&&0===s.length)&&_(119,[e]),function(e){e.includes("**")&&H(e);let t=e.split(".").length;t>512&&_(117,[e,t])}(r),{Je:r,Qe:n}}var z=[["$watch","temporal"],["$stream","temporal"],["$listKeys","list-keys"],["$recursion","recursion"]],D=["enableMustache","sameValueGuard","enableDirectionalInitialSync"];function U(e){return e.includes("**")&&H(e),e}var F=0;function q(e,t,n){let r=e.get(t);return void 0===r&&e.set(t,r=n()),r}var B=()=>new Set,K=()=>[];function G(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}function V(e,t){return e===t||e!=e&&t!=t}function J(e,t,n){let r=e.q?.get(t);void 0!==r&&r.delete(n)&&0===r.size&&e.q.delete(t)}function Q(e,t){for(let n=0;n<t.length;n++){if(null==e)return;e=e[t[n]]}return e}function X(e,t){for(;null!==e&&e.l.n>t;)e=e.l.re;return null!==e&&e.l.n===t?e:null}function Y(e,t,n){let r=X(e,n);return null!==r&&r.l.o===t.f[n]?r:null}var Z=class{constructor(e,t){this.Oe=0,this.c=null,this.Ce=0,this.mt=new Set,this.Ze=new Map,this.Dn=Symbol("wcs.block"),this.element=null,this.ht=[],this.Ie=null,this.Mn=[],this._t=0,this.K=null,this.ee=new Map,this.ie=new Map,this.je=[],this.Le=[],this.Be=[],this.yt=!1,this.dn=!1,this.Wt=new WeakMap,this.M=0,this.Ht=0,this.fn=!1,this.Vt=!1,this.Ut=!1,this.xe=0,this._n=()=>{this.M=0,this.fn=!1},this.Wn=()=>{this.xe--},this.rp=null,this.rr=null,this.Oo=()=>this.qt(),this.Co=(e,t)=>e(this.proxy,...t),this.Hn=[],this.Io={$untracked:e=>{let t=this.K;if(null===t)return e();t.pe++;try{return e()}finally{t.pe--}},$eqIndex:(e,t=1)=>{let n=X(this.c,t);null===n&&_(7,[e]);let r=this.o(e);if(null!==r.getter||r.de)return this.watchIndex(t),n.b===this.read(r,null);let i=this.K;if(null!==i){let e=i.getter,n=r.Fe??(r.Fe=[]);if(!n.some(n=>n.getter===e&&n.Vn===t)){n.push({getter:e,Vn:t});let i=e.f[t];(i.Tt??(i.Tt=[])).push({source:r,getter:e})}}return n.b===this.v(r,null)},$eq:(e,t)=>this.eq(e,t),$eqPath:(e,t)=>{let n=this.o(t);return this.eq(e,this.v(n,X(this.c,n.n)))},$dependOn:e=>{this.resolve(U(e),this.c),null!==this.K&&0===this.K.pe&&this.Un(this.rp,this.rr,this.K)},$getAll:(e,t)=>this.getAll(e,t),$setAll:(e,t,n,r)=>this.pn(e,t,n,r),$resolve:(...e)=>{let t=U(e[0]),n=e[1]??[],r=this.o(t);this.mn("$resolve",t,r,n,!0);let i=this.qn(r,n,null);if(e.length<3)return this.read(r,i);this.P(r,i,e[2])},$postUpdate:e=>{this.resolve(U(e),this.c);let t=this.rp,n=this.rr;"*"===t.s&&null!==n&&(n.T=n.l.C[n.b],this.R.Kt(n)),this.hn(t,n),null!==n&&this.Kn(n,t,void 0,n.T,!1),0===t.n&&this.zn(t,void 0,void 0,!0),this.zt(t,n,void 0,void 0,!1)}},this.R=t,this.B=new i(e=>this.et(e)),this.Xn(e);let n=this,r={getOwnPropertyDescriptor(e,t){let r=Reflect.getOwnPropertyDescriptor(n.target,t);return r&&(r.configurable=!0),r},get(e,t,r){let i=n.target;if("symbol"==typeof t)return Reflect.get(i,t);if(36===t.charCodeAt(0))return n.tt(t);if(t.indexOf(".")<0){let e=n.B.Ct(t);if(void 0===e||null===e.getter){let e=i[t];if("function"==typeof e)return r===n.proxy&&n._?.(e)||e}if(void 0!==e&&0===e.n)return n.read(e,null)}return n.resolve(t,n.c),n.read(n.rp,n.rr)},set:(e,t,r)=>"symbol"==typeof t?Reflect.set(n.target,t,r):(n.resolve(U(t),n.c),n.P(n.rp,n.rr,r),!0)};for(let e of["has","ownKeys","deleteProperty","defineProperty","getPrototypeOf"])r[e]=(t,...r)=>Reflect[e](n.target,...r);this.proxy=new Proxy({},r)}o(e){return this.B.get(e)}Yn(e){let t=new Set;for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n))for(let e of Object.getOwnPropertyNames(n)){if(t.has(e))continue;t.add(e);let r=Object.getOwnPropertyDescriptor(n,e);if(void 0===r.get&&void 0===r.set)continue;let i=this.o(e);i.getter=r.get??null,i.oe=r.set??null,null!==i.getter&&i.n>0&&(i.F=this.Oe++)}for(let e of this.B.all())this.et(e)}et(e){e.t.includes("**")&&H(e.t),("__proto__"===e.s||"prototype"===e.s)&&_(120,[e.t]);let t=e.d;e.de=null!==t&&"*"!==e.s&&t.n===e.n&&(null!==t.getter||t.de),null===e.getter&&this.jo(e)}jo(e){let t=e.t,n=e.s;if(x.test(n))e.getter=function(){return this[n]};else{let r=t.split("."),i=r.findIndex((e,t)=>t>0&&e.charCodeAt(0)>=48&&e.charCodeAt(0)<=57);if(i<0||r.indexOf("*",i)>=0)return;e.getter=()=>(this.resolve(t,this.c),this.rp!==e?this.read(this.rp,this.rr):this.read(e.d,this.c)?.[n]),e.oe=r=>{if(this.resolve(t,this.c),this.rp!==e)return this.P(this.rp,this.rr,r);let i=this.read(e.d,this.c);null==i&&_(4,[t,i]),i[n]=r}}e.n>0&&(e.F=this.Oe++)}De(e,t){let n=null===e?this.ee:e.h??=new Map,r=n.get(t);return void 0===r&&n.set(t,r=new a(t,e)),this.z(r),r}Gn(e){try{this.z(e)}catch(t){this.Xt(t,e.o.t,e.$?.S??null,"for")}}z(e){let t=this.v(e.o,e.re);if(t===e.C)return;this.Jn(e);let n=function(e,t,n){let r=Array.isArray(t)?t:u;if(r===e.C)return null;let i=e.u,s=r.length,o=i.length,a=new Array(s),c=0;for(;c<s&&c<o&&i[c].T===r[c];)a[c]=i[c],c++;let h=o-1,d=s-1;for(;h>=c&&d>=c&&i[h].T===r[d];)a[d]=i[h],h--,d--;if(c>h)for(let t=c;t<=d;t++)a[t]=new l(e,t,r[t]);else if(c>d)for(let e=c;e<=h;e++)n.jt(i[e]);else{let t=new Map;for(let e=c;e<=h;e++){let n=i[e],r=t.get(n.T);void 0===r?t.set(n.T,n):Array.isArray(r)?r.push(n):t.set(n.T,[r,n])}for(let n=c;n<=d;n++){let i,s=r[n],o=t.get(s);void 0!==o&&(Array.isArray(o)?(i=o.shift(),0===o.length&&t.delete(s)):(i=o,t.delete(s))),a[n]=i??new l(e,n,s)}for(let e of t.values())if(Array.isArray(e))for(let t of e)n.jt(t);else n.jt(e)}for(let e=c;e<s;e++){let t=a[e];t.b!==e&&(t.b=e,n.To(t))}return e.u=a,e.C=r,i}(e,t,this);if(null===n)return;if(e.C===t){let n=q(this.Wt,t,K);if(n.push(e),n.length>1)for(let e of n)e.ft=!0}c.Yt?.(this,e,n),(null!==e.$||null!==e.L)&&!e.Z&&(e.Z=!0,this.Le.push(e),this.Re());let r=e.o.Tt;if(null!==r)for(let{source:t,getter:i}of r){let r=this.v(t,null),s=n[r],o=e.u[r];s!==o&&(void 0!==s&&s.y&&this.gn(i,s),void 0!==o&&this.gn(i,o))}}To(e){this.R.Lo(this,e)}jt(e){e.y=!1;let t=e.q;if(null!==t){for(let e of t)J(e.source,e.key,e.sub);e.q=null}if(null!==e.h)for(let t of e.h.values()){this.Jn(t);for(let e of t.u)this.jt(e)}}Jn(e){let t=this.Wt.get(e.C);void 0!==t&&(t.splice(t.indexOf(e)>>>0,1),e.ft=!1,1===t.length&&(t[0].ft=!1))}resolve(e,t){let n=o(e),r=this.rp=this.o(n.o),i=n.indexes;this.rr=0===r.n?null:null===i?Y(t,r,r.n):this.qn(r,i,t,e)}qn(e,t,n,r){let i=null;for(let s,o=1,l=0;o<=e.n;o++){let a=e.f[o],c=this.De(i,a),h=t[l++];if(h<0)h=Y(n,e,o)?.b??-1;else if(r&&c.C===u&&Object(s=this.v(a,i))===s){let t=e.t.split("."),n=a.t.split(".").length;t[n]=r.split(".")[n],e=this.o(t.join(".")),o--;continue}if(i=c.u[h]??null,null===i)break}return this.rp=e,i}wt(e,t){return 0===e.n?Q(this.target,e.U):null===t?void 0:Q(t.T,e.U)}read(e,t){let n=this.K;if(null!==n&&0===n.pe&&this.Un(e,t,n),null!==e.getter)return this.R.Bo(this,e,t);if(e.de){let n=this.read(e.d,t);return n?.[e.s]}return null===e.d&&!(e.s in this.target)&&!this.mt.has(e.s)&&"then"!==e.s&&"toJSON"!==e.s&&_(301,[e.t],e.s,Object.keys(this.target)),this.wt(e,t)}v(e,t){let n=this.K;if(null===n)return this.read(e,t);n.pe++;try{return this.read(e,t)}finally{n.pe--}}Un(e,t,n){let r=n.getter;e.jn(r),e.n>0&&r.n>0&&X(t,Math.min(e.n,r.n))!==X(n.r,Math.min(e.n,r.n))&&(r.ut??(r.ut=new Set)).add(e)}Do(e,t){for(let n=0;n<this._t;n++){let r=this.Mn[n];r.getter===e&&r.r===t&&_(701,[e.t])}this._t>=128&&_(801,[e.t]);let n=this._t++;this.Ce++;let r=this.Mn[n]??={getter:e,r:t,pe:0,Me:0};r.getter=e,r.r=t,r.pe=0,r.Me=++F;let i=this.K;this.K=r;let s=this.c;this.c=t;try{return e.getter.call(this.proxy)}finally{this.Ce--,this._t--,this.K=i,this.c=s,r.r=null}}watchIndex(e){let t=this.K;if(null!==t&&0===t.pe){let n=t.getter,r=n.f[e];if(r){let e=r.At??(r.At=[]);e.includes(n)||e.push(n)}}}tt(e){let t=e.charCodeAt(1);if(t>=48&&t<=57){let n=2===e.length?t-48:x.test(e)?+e.slice(1):0;return(n<1||n>128)&&_(1001,[e]),this.watchIndex(n),X(this.c,n)?.b}let n=this.Io[e];if(void 0!==n)return n;switch(e){case"$stateElement":return this.element;case"$command":return this.commands}return c.tt?.(this,e)}eq(e,t){this.resolve(e,this.c);let n=this.rp,r=this.rr;if(null!==n.getter||n.de||n.n>0)return V(this.read(n,r),t);let i=this.K;return null!==i&&0===i.pe&&this.Mo(n,t,i),V(this.v(n,null),t)}Mo(e,t,n){let r=n.getter,i=n.r,s=null===i?this.Hn:i.q??(i.q=[]);for(let i=0;i<s.length;i++){let o=s[i];if(o.sub.getter===r&&o.source===e){if(V(o.key,t))return void(o.Me=n.Me);o.Me!==n.Me&&(J(e,o.key,o.sub),s.splice(i--,1))}}let o={getter:r,r:i};q(e.q??=new Map,t,B).add(o),s.push({source:e,key:t,sub:o,Me:n.Me})}zn(e,t,n,r){this.Gt(e,i=>{let s=i.q;if(null===s&&null===i.Fe)return;let o=i===e?[]:i.t.slice(e.t.length+1).split("."),l=Q(t,o),a=Q(n,o);if(null!==i.Fe&&this._o(i,l,a,r),null!==s)for(let e of r?s.keys():[l,a]){let t=s.get(e);if(void 0!==t)for(let n of t)null===n.r||n.r.y?this.R.me(this,n.getter,n.r):J(i,e,n)}})}P(e,t,n,r=!1,i=!1){if(this.Ce>0&&_(8),i||this.xe>0?this.Vt=!0:this.Ut=!0,c.Pe?.(this,e,t,n,i))return;if(null!==e.oe){try{this.yn(e.oe,t,[n])}finally{this.zt(e,t,void 0,void 0,!1)}return}null!==e.getter&&_(2,[e.t]),e.n>0&&null===t&&_(3,[e.t]);let s=e.de?this.v(e,t):this.wt(e,t);if(r||!this.Dt||!Object.is(s,n)||Object(n)===n){if("*"===e.s){let e=t;e.l.C[e.b]=n,e.T=n,this.R.Kt(e)}else{let r=1===e.U.length?0===e.n?this.target:t.T:this.v(e.d,t);null==r&&_(4,[e.t,r]),r[e.s]=n}this.wn(e,t),null!==t&&this.Kn(t,e,s,n),0===e.n&&this.zn(e,s,n),this.zt(e,t,s,n,!0)}}Qn(e){return(this.Wt.get(e.C)??[]).filter(t=>t.C===e.C&&(null===t.re||t.re.y))}Kn(e,t,r,i,s=!0){let o=e.l;if(!o.ft&&null===o.o.getter&&!o.o.G.length)return;let l=e.T,a=t.t.slice(o.o.t.length+2),u=(t,n)=>{if(void 0===n||n===e)return;let o=this.o(`${t.o.t}.*${a}`);""===a&&(n.T=i,this.R.Kt(n)),s?this.wn(o,n):this.hn(o,n),this.zt(o,n,r,i,s)};for(let t of this.Qn(o))u(t,t.u[e.b]);if(""===a)return;let c=new Set([o.C]),h=e=>Array.isArray(e)&&e.includes(l),d=(e,t)=>{if(!c.has(e)&&c.add(e))for(let t of this.Wt.get(e)??[])for(let e of t.u)e.T===l&&u(t,e);for(let r of t){let t=r.J,i=t===n;i&&(t=this.ee.get(r)?.C),(i||h(t))&&!c.has(r.G)&&c.add(r.G)&&(!i&&t!==e&&this.R.me(this,r,null),d(t,r.G))}},f=e=>{for(let t of e.$e)if(!c.has(t)&&c.add(t))if(null!==t.getter)f(t);else if(!t.de){let e=this.wt(t,null);h(e)&&d(e,t.G)}};null!==o.o.getter?f(o.o):d(o.C,o.o.G)}hn(e,t){this.Wo(e,t,e=>{this.z(e);for(let t of e.ft?this.Qn(e):[e]){let e=this.o(`${t.o.t}.*`);for(let n of t.u)this.bt(e,n),this.hn(e,n)}})}wn(e,t){let n=null===t?this.ee:t.h;if(null!==n)for(let t of n.values())t.o.Q(e)&&this.z(t)}Wo(e,t,n){let r=null===t?this.ee:t.h;if(null!==r)for(let t of r.values())t.o.Q(e)&&n(t)}_o(e,t,n,r){for(let{getter:i,Vn:s}of e.Fe)this.Zn(i.f[s],e=>{for(let s of r?e.u.keys():[t,n]){let t="number"==typeof s?e.u[s]:void 0;void 0!==t&&this.gn(i,t)}})}gn(e,t){t.l.n===e.n?this.R.me(this,e,t):this.Jt(t,e,t=>this.R.me(this,e,t))}zt(e,t,n,r,i){c.he?.(this,e,t,n,r,i),this._e(e,t)}_e(e,t){this.R.Ho(this,e,t),this.Re()}eo(e){let t=this.Ze.get(e);if(void 0!==t)return t;let n=Symbol(`wcs.on${e}`);this.Ze.set(e,n);let r=this.root,i=this.Dn;return r.addEventListener(e,t=>{for(let s=t.target;null!==s&&s!==r;s=s.parentNode){let r=s[n];if(void 0!==r&&(r(t),t.cancelBubble))return;let o=s[i];if(void 0!==o&&o.y&&o.Vo(e,t))return}}),n}reset(e){let t=this.target,n=this.mt;for(let e of this.B.all())null===e.d&&null!==e.getter&&n.add(e.s);this.Xn(e);for(let e in t)"$"!==e[0]&&n.add(e);for(let t of n)t in e&&n.delete(t);for(let e of this.ie.values())for(let t of e)this.Qt(t);for(let e of this.ee.values())this.to(e);this.Ie=null;try{this.qt()}finally{this.bn()}c.element?.(this,"reset")}Xn(e){for(let[t,n]of z)void 0!==e[t]&&b(n,t);let t=e.$features;if(void 0!==t){Array.isArray(t)||_(46);for(let e of t)b(e,"$features")}let n=void 0===e.$behavior?{}:e.$behavior;("object"!=typeof n||!n||Array.isArray(n))&&_(44,["state","$behavior"]);for(let e in n)(!D.includes(e)||"boolean"!=typeof n[e])&&_(44,["$behavior",e]);let[r,i,s]=D.map(e=>n[e]??!0);void 0!==this.target&&(r!==this.Bt||i!==this.Dt||s!==this.Mt)&&_(45);let o=function(e,t){let n={};for(let r of k(e.$commandTokens,"$commandTokens","$command"))n[r]=t?.[r]??new $(r);return Object.freeze(n)}(e,this.commands),l=function(e,t){let n=new Map;for(let t of k(e.$eventTokens,"$eventTokens"))n.set(t,new $(t));let r=e.$on;if(void 0===r)return n;(null===r||"object"!=typeof r)&&_(22);for(let[e,i]of Object.entries(r)){let r=n.get(e);void 0===r&&_(23,[e]),"function"!=typeof i&&_(24,[e]),r.subscribe((...e)=>t(i,e))}return n}(e,this.Co);this.Bt=r,this.Dt=i,this.Mt=s,c.se?.(this,e),this.target=e,this.Oe=0;for(let e of this.B.all())e.Po();this.Hn.length=0,this.Yn(e),this.commands=o,this.Ne=l}to(e){this.Gn(e);let t=this.o(`${e.o.t}.*`);for(let n of e.u)if(n.dt=null,n.q=null,this.bt(t,n),null!==n.h)for(let e of n.h.values())this.to(e)}W(e){let t=[];for(let n=e;null!==n;n=n.l.re)t.unshift(n.b);return t}Uo(e,t,n){let r=this.Ne.get(e);void 0===r&&_(1301,[e],e,this.Ne.keys()),r.emit(t,...this.W(n))}command(e){let t=this.commands[e];return void 0===t&&_(1302,[e],e,Object.keys(this.commands)),t}qo(e,t,n){this.command(e).emit(t,...this.W(n))}Ko(e,t,n){let r=e.includes(".")?this.v(this.o(e),null):this.target[e];return"function"!=typeof r&&_(5,[e]),this.yn(r,n,[t,...this.W(n)])}yn(e,t,n){let r=this.c;this.c=t;try{return e.apply(this.proxy,n)}finally{this.c=r}}bt(e,t){if(null!==e.getter){let n=null===t?this.ee:t.h;if(null!==n)for(let t of n.values())!t.It&&t.o.Q(e)&&(t.It=!0,this.Be.push(t))}if(null===t)return void this.Gt(e,e=>{let t=this.ie.get(e);if(void 0!==t)for(let e of t)this.Qt(e)});let n=t.fe;if(null!==n)for(let t=0;t<n.length;t++)n[t].o.Q(e)&&this.Qt(n[t]);let r=t.$;null!==r&&null!==r.ae&&r.no(this,e);let i=t.l.L;if(null!==i)for(let n of i){let r=n.map.get(t);void 0!==r&&null!==r.ae&&r.no(this,e)}}vn(e,t,n){this.Gt(e,e=>{let r=e.G;for(let i=0;i<r.length;i++){let s=r[i];if(0===s.n)this.nt(s,null,n);else if(null===t||0===e.n||s.f[1]!==e.f[1]||null!==s.ut&&s.ut.has(e))this.Zt(s.f[s.n],e=>this.nt(s,e,n));else if(s.n<=e.n){let e=X(t,s.n);null!==e&&this.nt(s,e,n)}else this.Jt(t,s,e=>this.nt(s,e,n))}})}nt(e,t,n){n(e,t)&&(c.ye?.(this,e,t),this.bt(e,t),this.vn(e,t,n))}Gt(e,t){t(e);let n=e.h;for(let e=0;e<n.length;e++)this.Gt(n[e],t)}Zt(e,t){this.Zn(e,e=>{for(let n of e.u)t(n)})}Zn(e,t){if(0===e.n){let n=this.ee.get(e);return void(void 0!==n&&t(n))}this.Zt(e.f[e.n],n=>{let r=n.h?.get(e);void 0!==r&&t(r)})}Jt(e,t,n){if(e.l.n===t.n)return n(e);let r=e.h?.get(t.f[e.l.n+1]);if(void 0!==r)for(let e of r.u)this.Jt(e,t,n)}zo(e){let t=e.r;null===t?q(this.ie,e.o,B).add(e):(t.fe??(t.fe=[])).push(e)}kn(e){let t=e.r;if(null===t)return void this.ie.get(e.o)?.delete(e);let n=t.fe;t.y&&null!==n&&n.splice(n.indexOf(e)>>>0,1)}Qt(e){e.Z||(e.Z=!0,this.je.push(e),this.Re())}Re(){this.yt||(this.yt=!0,queueMicrotask(this.Oo))}Sn(){for(let e of this.je)e.Z=!1;for(let e of this.Le)e.Z=!1;for(let e of this.Be)e.It=!1;this.je=[],this.Le=[],this.Be=[],this.R.mt(this)}oo(e,t){let n=[...new Set([...this.je,...this.Le,...this.Be].map(e=>e.o.t))];console.error(`[@wcstack/state] ${w(e)}`,n),c.ot?.(this,{type:"state:render-chain-limit",maxDepth:t,paths:n}),this.Sn()}qt(){this.yt=!1;let e=this.Ht;this.Ht=0;let t=0;if(!this.Vt||this.Ut?this._n():e>0?t=e:1===(t=++this.M)&&setTimeout(this._n,0),this.Vt=this.Ut=!1,t>100)101===t?this.oo(41,100):this.Sn();else{this.dn=!0;try{for(let e=0;this.je.length>0||this.Le.length>0||this.Be.length>0;e++){if(e>=32){this.fn?this.Sn():this.oo(11,32),this.fn=!0;break}let n=this.Be;if(n.length>0){this.Be=[];for(let e of n)e.It=!1,this.Gn(e)}let r=this.Le,i=this.je;this.Le=[],this.je=[];let s=E("state",()=>{for(let e of r){e.Z=!1;for(let t of[e.$,...e.L??[]])if(null!==t&&t.y)try{t.vt()}catch(n){this.Xt(n,e.o.t,t.S,"for")}}for(let e=0;e<i.length;e++){let t=i[e];t.Z&&(t.Z=!1,(null===t.En||t.En.y)&&this.We(t))}this.dn||(this.He(),this.yt&&(this.Ht=t+1))});void 0!==s&&s.then(void 0,e=>console.error(e))}}finally{this.dn=!1}this.Vt=this.Ut=!1,this.He(),c.Te?.(this),e>0&&this.yt&&(this.Ht=t+1)}}kt(e,t){this.ht.push([e,t])}Xt(e,t,n,r){this.kt(e,{o:{t:t},a:n,en:()=>r})}We(e){try{e.apply()}catch(t){return void this.ht.push([t,e])}null!==this.Ie&&this.io(e.o,e.r)}io(e,t){let n=q(this.Ie,e.t,K);null!==t&&n.push(this.W(t))}bn(){this.Ie="function"==typeof this.target.$renderedCallback?new Map:null}He(){let e=this.Ie;if(null!==e&&e.size>0){this.Ie=new Map;let t,n=[...e.keys()],r={};for(let[t,n]of e)n.length>0&&(r[t]=n);this.xe++;try{t=this.we("$renderedCallback",[n,r])}catch(e){console.error(e)}G(t)?t.then(this.Wn,e=>{this.Wn(),console.error(e)}):this.xe--}if(0===this.ht.length)return;let t=this.ht;this.ht=[];let n=this.target.$errorCallback;for(let[r,i]of t){c.Ve?.(this,r,i);let t=i.o.t,s=i.en();if("function"==typeof n)try{let e=this.we("$errorCallback",[r,{path:t,bindingType:s,node:i.a}]);G(e)&&e.then(void 0,e=>console.error(e))}catch(e){console.error(e)}else console.error(`[@wcstack/state] ${w(12,[s,t])}`,r)}}we(e,t=[]){let n=this.target[e];return"function"==typeof n?this.yn(n,null,t):void 0}so(e,t,n){if(0===e.n)return void n(null,[]);let r=[],i=(s,o)=>{let l=e.f[s];this.read(l,o);let a=this.De(o,l),u=t=>{r.push(t.b),s===e.n?n(t,r):i(s+1,t),r.pop()};for(let e of s-1<t.length?[a.u[t[s-1]]]:a.u)void 0!==e&&u(e)};i(1,null)}getAll(e,t){let n=this.o(e);void 0!==t&&this.mn("$getAll",e,n,t,!1);let r=t;if(void 0===r){r=[];let t=this.c;if(null!==t&&n.n>0){for(let e=1;e<=n.n;e++){let i=Y(t,n,e);if(null===i)break;r.push(i.b)}0===r.length&&_(6,[e])}}let i=[];return this.so(n,r,e=>i.push(this.read(n,e))),i}pn(e,t,n,r){Array.isArray(t)||_(9,[e]),this.Ce>0&&_(8);let i=this.o(e);this.mn("$setAll",e,i,t,!1);let s=[];this.so(i,t,(e,t)=>s.push([e,t.slice()]));let o=!0===r?.spread;o&&(!Array.isArray(n)||n.length!==s.length)&&_(10,[e,s.length]);let l=0;for(let e=0;e<s.length;e++){let[t,r]=s[e],a="function"==typeof n?n(this.v(i,t),...r):o?n[e]:n;void 0!==a&&(this.P(i,t,a),l++)}return l}mn(e,t,n,r,i){let s=r.length;(s>n.n||i&&s<n.n)&&_(i?901:902,[e,t,n.n,s])}},ee={bindAttributeName:"data-wcs",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:typeof document<"u"&&document.documentElement?.lang||"en"},te=new Map,ne=new Set(["if","elseif","else","for"]),re=new Set([A,"if","elseif","for","..."]),ie=new Set(["class","attr","style","command",C,"state"]);function se(e){let t=function(e){return I(e,";")}(e).map(O).filter(e=>e.length>0).map(e=>{let t=M(e,":");-1===t&&_(101,[e]);let n=e.slice(0,t).trim(),r=e.slice(t+1).trim(),i=n.split("#")[0].split("|")[0].trim();if(re.has(i)){let t;return i!==n&&_(102,[e,i]),i===A?(r.length>0&&_(103,[e]),t={Je:"#else",Qe:[]}):"..."===i?(0===r.length&&_(104,[e]),t=W(r),t.Qe.length>0&&_(105,[e])):(t=W(r),"for"===i&&t.Qe.length>0&&_(121,[e])),{be:i,ve:[i],tn:[],I:[],...t,w:"..."===i?"spread":i}}let s=W(r),o=function(e){let[t,n]=j(e,"input",te),r=t.split("#").map(O);r.length>2&&_(115,[t]);let[i,s]=r,o=i.split(".").map(O);return!(o.length>1&&""===o[0])&&(0===i.length||o.some(e=>0===e.length))&&_(116,[e]),{be:i,ve:o,tn:s?s.split(",").map(O):[],I:n}}(n),[l]=o.ve;if(""===l&&o.ve.length>1){let e=o.ve.slice(1);return(e.includes("")||ie.has(e[0]))&&_(106,[n]),{...o,be:e.join("."),ve:e,...s,w:"prop"}}return{...o,...s,w:"radio"===i||"checkbox"===i?i:l===C||l.startsWith("on")?"event":"prop"}});return t.length>1&&t.some(e=>ne.has(e.w))&&_(201,[e]),t}var oe=["toFixed","locale","upper","lower","capitalize","trim","slice","padStart","padEnd","repeat","reverse","truncate","join","round","floor","ceil","percent","unit","date","time","datetime","ymd","hms","add","sub","mul","div","mod","abs","clamp","int","float","defaults","coalesce","number","string","nullIfEmpty"],le=new Map,ae=new Map;function ue(e){for(let t of Object.keys(e))le.set(t,{...e[t]});ae.clear()}function ce(e){return le.has(e)}function he(e){_(26,[e])}function de(e){_(27,[e])}function fe(e){_(28,[e])}function pe(e){_(29,[e])}function me(e){return!(!e||isNaN(Number(e)))}function ge(e,t){return me(e)||de(t),Number(e)}function ye(e,t,n){return ge(e?.[t]??he(n),n)}function be(e,t){return void 0!==t&&t.length>0?t[0]:e}var ve=(e,t)=>({factory:n=>{let r=ye(n,0,e);return n=>("number"!=typeof n&&fe(e),t(n,r))},arity:[1,1]}),we={eq:{factory:(e,t)=>{let n=e?.[0]??he("eq"),r=be(n,t);return e=>"number"==typeof e?"string"!=typeof r?e===r:(me(n)||de("eq"),e===Number(n)):"string"==typeof e?e===n:e===r},arity:[1,1]},ne:{factory:(e,t)=>{let n=e?.[0]??he("ne"),r=be(n,t);return e=>"number"==typeof e?"string"!=typeof r?e!==r:(me(n)||de("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==r},arity:[1,1]},not:{factory:()=>e=>!e,arity:[0,0]},lt:ve("lt",(e,t)=>e<t),le:ve("le",(e,t)=>e<=t),gt:ve("gt",(e,t)=>e>t),ge:ve("ge",(e,t)=>e>=t),falsy:{factory:()=>e=>!e,arity:[0,0]},truthy:{factory:()=>e=>!!e,arity:[0,0]},boolean:{factory:()=>e=>!!e,arity:[0,0]}},_e=!1;function $e(e,t){if(null!==e)for(let n=0;n<e.length;n++)t=e[n](t);return t}function ke(e){return 0===e.length?null:(_e||(_e=!0,ue(we)),e.map(e=>function(e,t,n){let r=`${e}${function(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}(t,n)}`,i=ae.get(r);if(typeof i<"u")return i;let s=le.get(e);void 0===s&&function(e,t){oe.includes(e)&&v(`[wcs/filter-unknown] filter not found: ${e}. "${e}" is in the formats add-on — install it with installFeatures([formats]) from "@wcstack/state/features/formats".`,e,t),_(501,[e],e,t)}(e,le.keys());let[o,l]=s.arity;t.length<o&&_(601,[e,o,t.length]),t.length>l&&_(602,[e,l,t.length]);let a=s.factory(t,n);return ae.set(r,a),a}(e.Bn,e.args,e.literals)))}var Se=Symbol.for("wcstack.trustedTypes.policy");function Ne(){let e=globalThis[Se];return null!==e&&"object"==typeof e?e:null}function Ee(e){return"innerHTML"===e||"outerHTML"===e||"srcdoc"===e}function Ae(e){if(globalThis.trustedTypes?.isHTML(e))return e;let t=null==e?"":String(e),n=Ne(),r=n?.createHTML;return"function"==typeof r?r.call(n,t):t}var Ce=Symbol.for("wcstack.state.view-transition-naming"),xe=new WeakSet;function Te(){let e=N("state");return null!==e&&"auto"===e.naming?e.namingLimit:-1}var Pe=new WeakMap,Oe=e=>e.customElementRegistry??customElements;function Le(e,t,n,r,i,s=!1){let o=n.localName;if(!o.includes("-"))return i(null);let l=Oe(n);if(!s&&!n.isConnected&&void 0===l.get(o)&&"customElementRegistry"in n)return void queueMicrotask(()=>Le(e,t,n,r,i,!0));let a=()=>{let e=l.get(o);l.upgrade(n),i(e?function(e){if(Pe.has(e))return Pe.get(e);let t=e.wcBindable,n=null;if(null!==t&&"object"==typeof t&&"wc-bindable"===t.protocol&&Number.isInteger(t.version)&&t.version>=1){n={properties:new Map,inputs:new Map,commands:new Set};for(let e of t.properties??[])n.properties.set(e.name,{event:e.event,getter:"function"==typeof e.getter?e.getter:null,lo:"event"===e.semantics});for(let e of t.inputs??[])n.inputs.set(e.name,{attribute:"string"==typeof e.attribute?e.attribute:null});for(let e of t.commands??[])null!==e&&"object"==typeof e&&"string"==typeof e.name&&n.commands.add(e.name)}return Pe.set(e,n),n}(e):null)};if(!s&&void 0!==l.get(o))return a();null!==r&&!r.y||function(e,t,n){let r=n;null!==t&&(t.St??=[]).push(()=>{r=null}),e.then(()=>r?.())}(l.whenDefined(o),r,()=>{try{a()}catch(r){We(e,r,t,n)}e.Re()})}function Me(e,t,n,r,i=t.o,s,o,l){let a=l.properties.get(r)??null,u=l.inputs.get(r),h=e.Mt;h&&null===a&&void 0===u&&_(38,[r]);let d=t.H;(null===a?"element"===d||"auto"===d:void 0===u&&("state"===d||"auto"===d))&&_(39,[d,r]),"connect"===t.z&&null===a&&_(40,[r]);let f=h&&null!==a&&void 0===u,p=new Ue(e,Re,n,r,i,s,o,t.N,void 0);p.I=t.I,p.attribute=u?.attribute??null,Qe(e,p,!f),null!==a&&!t.ro&&n.addEventListener(a.event,t=>{let i;null!==a.getter?i=a.getter(t):(i=t.detail,a.lo||c.detail?.(n,r,i)),(!p.$n||!Object.is(i,p.value))&&(i=$e(p.I,i),null===p.N&&(p.value=i),e.P(p.o,p.r,i,a.lo,!0))});let m=d??(f?"element":"state");if("state"===m)f||e.We(p);else if("element"===m||"auto"===m){let i=()=>{if(null!==o&&!o.y)return;if("auto"===m&&void 0!==e.v(p.o,p.r))return void(f||e.We(p));let t=n[r];null===p.N&&(p.value=t),e.P(p.o,p.r,t,!1,!0)};"connect"!==t.z||n.isConnected?i():Promise.resolve().then(i)}return p}function Ie(e,t,n){_(e,[t.localName,n])}var je=new Set(["click","dblclick","input","change","submit","keydown","keyup","mousedown","mouseup","pointerdown","pointerup"]),Re=11,He=["text","prop","prop","prop","prop","event","for","if","prop","radio","checkbox","prop","prop","event","spread"],We=(e,t,n,r)=>e.Xt(t,n.o?.t??n.Et,r,He[n.i]),ze=Symbol();function De(e,t,n){let r=t.H;return null===r||"state"===r||"auto"===r&&void 0!==e.v(t.o,n)?t.V:ze}var Ue=class{constructor(e,t,n,r,i,s,o,l,a,u=null){this.Z=!1,this.I=null,this.attribute=null,this.$n=!1,this.engine=e,this.i=t,this.a=n,this.name=r,this.o=i,this.r=s,this.En=o,this.N=l,this.value=a,this.M=u}en(){return He[this.i]}apply(){if(null!==this.M)return void this.M.vt();let e=$e(this.N,this.engine.read(this.o,this.r));if(e===this.value&&("object"!=typeof e||null===e||this.i===Re||8===this.i||Ee(this.name)))return;if(this.value===ze)return void(this.value=e);let t=this.a;if(this.i!==Re)9===this.i?t.checked=void 0!==e&&this.nn()===e:10===this.i?t.checked=Array.isArray(e)&&e.includes(this.nn()):qe(this.i,t,this.name,e),this.value=e;else{if(void 0===e)return void(this.value=e);this.value=e,this.$n=!0;try{t[this.name]!==e&&(t[this.name]=e)}finally{this.$n=!1}null!==this.attribute&&function(e,t,n){try{if(null==n)e.removeAttribute(t);else{let r=n;if("object"==typeof n)try{r=JSON.stringify(n)}catch{}e.setAttribute(t,String(r))}}catch{}}(t,this.attribute,e)}}nn(){return $e(this.I,this.a.value)}Xo(){let e,t=this.a,n=this.engine;if(9===this.i){if(!t.checked)return;e=this.nn()}else if(10===this.i){let r=this.nn(),i=n.v(this.o,this.r),s=Array.isArray(i)?i:[],o=s.includes(r);if(t.checked?o:!o)return;e=o?s.filter(e=>e!==r):[...s,r]}else e=$e(this.I,t[this.name]);n.P(this.o,this.r,e,!1,!0)}},Fe=e=>"textContent"===e||"innerText"===e||"innerHTML"===e;function qe(e,t,n,r){switch(e){case 0:return void(t.data=null==r?"":String(r));case 1:return void(Fe(n)?t[n]="innerHTML"===n?Ae(r):null==r?"":String(r):Ee(n)?null==r&&"srcdoc"===n?t.removeAttribute(n):void 0!==r&&(t[n]=Ae(r)):void 0!==r&&(t[n]!==r&&!("value"===n&&t.value===String(r))&&(t[n]=r),("value"===n||"selectedIndex"===n)&&"select"===t.localName&&(t[Be]=[n,r])));case 8:return void(t.innerHTML=Ae(r));case 2:return null!=r&&"boolean"!=typeof r&&_(401,[n,typeof r]),void t.classList.toggle(n,!0===r);case 3:return void(null==r?t.removeAttribute(n):t.setAttribute(n,String(r)));case 4:return void(null==r?t.style.removeProperty(n):t.style.setProperty(n,String(r)))}}var Be=Symbol();function Ke(e){let t="optgroup"===e.localName?e.parentNode:e,n=t?.[Be];void 0!==n&&(t[n[0]]=n[1])}var Ge=class{constructor(e,t,n,r){this.y=!0,this.fe=null,this.h=null,this.St=null,this.xn=null,this.r=e,this.Ue=t,this.j=n,this.A=r}Vo(e,t){let n=t.target,r=this.A,i=[],s=null;for(let t of r.Ne){if(t.name!==e)continue;let o=r.Rn[t.a],l=st(null===this.j?this.Ue:this.j[o[0]],o,1);l.contains(n)&&(l!==s&&i.unshift([]),i[0].push(t),s=l)}for(let e of i){for(let n of e)n.Nn(t,this.r);if(t.cancelBubble)return!0}return!1}get s(){return null===this.j?this.Ue:this.j[this.j.length-1]}qe(){let e=this.xn;return(null===e?null:e.Pn(this.Ue))??this.Ue}insertBefore(e,t){let n=this.s;for(let r=this.qe();;){let i=r.nextSibling;if(e.insertBefore(r,t),r===n)return;r=i}}uo(){null===this.j?this.Ue.remove():ot(this.qe(),this.s)}Se(e){if(this.y=!1,null!==this.St)for(let e of this.St)e();let t=this.fe;if(null!==t)for(let n=0;n<t.length;n++)e.kn(t[n]);if(null!==this.h)for(let e of this.h)e.Se()}},Ve=class extends Ge{constructor(e,t,n,r){super(e,t,n,r),this.fo=0,this._=null,this.ae=0===r.Ke.length?null:new Array(2*r.Ke.length)}po(e,t){let n=this._??=new Array(this.A.Ke.length),r=n[t];if(void 0===r){let i=this.A.Ke[t],s=this.ae;r=n[t]=new Ue(e,i.i,s[2*t],i.name,i.o,this.r,this,i.N,s[2*t+1])}return r}no(e,t){let n=this.A.Ke;for(let r=0;r<n.length;r++)n[r].o.Q(t)&&e.Qt(this.po(e,r))}Se(e){let t=this.r;t.$===this&&(t.$=null),super.Se(e)}};function Je(e,t,n,r){let i=X(n,t.n);try{return e.De(i,t)}catch(n){return e.Xt(n,t.t,r,"for"),null===i?e.ee.get(t):i.h.get(t)}}function Qe(e,t,n){n&&e.zo(t);let r=t.En;null!==r&&(r.fe??=[]).push(t)}var Xe=null;function Ye(){let e=Xe;return Xe=null,e}var Ze=-1;function et(e,t,n,r,i=null){let s,o=t.Rn,l=t.build,a=t.mo,u=null,h=c.Ae?.(t,null===r?i:r.S,null!==r),d=!h&&t.Tn,f=h?document.createDocumentFragment():(d?t.root:t.on).cloneNode(!0);if(!h)for(let e=0;e<l.length;e++){let t=l[e];a[t]=st(f,o[t],d?1:0)}d?s=f:(u=h||[...f.childNodes],s=u[0]);let p,m=null;if(null!==r?(p=m=new Ve(n,s,u,t),null===r.map?n.$=m:r.map.set(n,m)):p=new Ge(n,s,u,t),Ze>=0&&function(e,t,n,r){let i=null;if(null===t)i=1===e.nodeType?e:null;else for(let e=0;e<t.length&&null===i;e++)1===t[e].nodeType&&(i=t[e]);let s=i?.style;if(null===i||void 0===s||xe.has(i))return;let o=globalThis[Ce]??={counter:0,assigned:0,warned:!1};o.assigned>=r?o.warned||(o.warned=!0,console.warn(`[@wcstack/state] ${w(25,[r])}`)):(xe.add(i),o.assigned++,s.setProperty("view-transition-name",`wcs-${n}-${++o.counter}`),s.setProperty("view-transition-class",`wcs-${n}`))}(s,u,null!==r?"row":"branch",Ze),t.Ne.length>0){let t=e.Dn;if(null===u)s[t]=p;else for(let e of u)1===e.nodeType&&(e[t]=p)}let g=t.Yo,y=e.Ie,b=t.Go?a.slice(0,o.length):a,v=null===m?null:m.ae;if(null!==v){let e=t.Ke;for(let t=0;t<e.length;t++)v[2*t]=b[e[t].a],v[2*t+1]=e[t].V}for(let r=0;r<g.length;r++){let i=g[r],o=b[i.a],l=i.F;if(l>=0&&null!==v){let r=m._?.[l];if(void 0!==r){r.Z=!1,e.We(r);continue}try{let t=$e(i.N,e.read(i.o,n));t!==i.V&&(qe(i.i,o,i.name,t),v[2*l+1]=t),null!==y&&e.io(i.o,n)}catch(t){e.kt(t,m.po(e,l))}continue}switch(i.i){case 6:{let t=new it(e,i.A,Je(e,i.o,n,o),o);(p.h??=[]).push(t),o===s&&(p.xn=t),t.vt();break}case 7:{let t=nt(e,i.X.map(e=>({A:e.A,o:e.o,N:e.N,S:b[e.a]})),n,p);(p.h??=[]).push(t),o===s&&(p.xn=t);break}default:try{tt(e,i,o,n,p)}catch(t){We(e,t,i,o)}}}return Xe=p,f}function tt(e,t,n,r,i){let s=n;switch(t.i){case 5:return void function(e,t,n,r,i){let s=n.Nn,o=e=>s(e,r);if(n.Ze){let r=e.eo(n.name),i=t[r];t[r]=void 0===i?o:e=>{i(e),o(e)},n.ke&&t.addEventListener(n.name,e=>e.bubbles||o(e))}else t.addEventListener(n.name,o),n.co&&null!==i&&(i.St??=[]).push(()=>t.removeEventListener(n.name,o))}(e,n,t,r,i);case 12:return void Le(e,t,s,i,n=>function(e,t,n,r,i){let s=t.name,o=e.command(t.Et.slice(9));null===i&&Ie(1202,n,`command.${s}`),i.commands.has(s)||_(1203,[n.localName,s]);let l=new WeakRef(n),a=o.subscribe((...e)=>{let t=l.deref();if(void 0!==t)return t.isConnected?t[s](...e):void 0;a()});null!==r&&(r.St??=[]).push(a)}(e,t,s,i,n));case 13:return void Le(e,t,s,i,n=>function(e,t,n,r,i){let s=t.name;null===i&&Ie(1202,n,`eventToken.${s}`);let o=i.properties.get(s);void 0===o&&_(1204,[n.localName,s]);let l=t.Et;n.addEventListener(o.event,n=>{t.$t&&n.preventDefault(),t.Nt&&n.stopPropagation();try{e.Uo(l,n,r)}catch(e){console.error(e)}})}(e,t,s,r,n))}let o=t.o,l=X(r,o.n);if(14===t.i)return void Le(e,t,s,i,n=>function(e,t,n,r,i,s){null===s&&Ie(1501,n,`"...: ${t.o.t}"`);let o=new Set([...s.properties.keys(),...s.inputs.keys()]);for(let l of o){if(t.ao?.includes(l))continue;let o=e.o(`${t.o.t}.${l}`),a=0===o.n?null:r;Me(e,{...t,H:null,z:null},n,l,o,a,i,s)}}(e,t,s,l,i,n));if(t.ke&&1===t.i)return void Le(e,t,s,i,n=>function(e,t,n,r,i,s){if(null!==s)return void Me(e,t,n,t.name,t.o,r,i,s);let o=new Ue(e,1,n,t.name,t.o,r,i,t.N,De(e,t,r));o.I=t.I,!c.Jo?.(o,t.ro)&&(Qe(e,o,!0),e.We(o))}(e,t,s,l,i,n));let a=new Ue(e,t.i,n,t.name,o,l,i,t.N,De(e,t,l));a.I=t.I,Qe(e,a,!0),e.We(a),null!==t.xt&&n.addEventListener(t.xt,()=>a.Xo())}function nt(e,t,n,r){let i=new rt(e,t,n),s=null;for(let o of t){if(null===o.o)continue;let t=o.o,l=new Ue(e,7,o.S,"if",t,X(n,t.n),r,null,void 0,i);Qe(e,l,!0),null===r&&i.ie.push(l),s??=l}return e.We(s),i}var rt=class{constructor(e,t,n){this.y=!0,this.O=null,this.b=-1,this.ie=[],this.engine=e,this.X=t,this.r=n}Pn(e){return null!==this.O&&this.X[this.b].S===e?this.O.qe():null}vt(){let e=this.engine,t=-1;for(let n=0;n<this.X.length;n++){let r=this.X[n];if(null===r.o||$e(r.N,e.read(r.o,X(this.r,r.o.n)))){t=n;break}}if(t!==this.b&&(Ze=Te(),null!==this.O&&(this.O.uo(),this.O.Se(e),this.O=null),this.b=t,t>=0)){let n=this.X[t],r=et(e,n.A,this.r,null,n.S);this.O=Ye();let i=n.S.parentNode;i.insertBefore(r,n.S),Ke(i)}}Se(){this.y=!1;for(let e of this.ie)this.engine.kn(e);null!==this.O&&this.O.Se(this.engine)}},it=class{constructor(e,t,n,r){this.y=!0,this.Ee=[],this.engine=e,this.A=t,this.l=n,this.S=r,null===n.$?(n.$=this,this.map=null):((n.L??=[]).push(this),this.map=new Map)}Pn(e){return 0===this.Ee.length?null:this.Ee[0].qe()}Rt(e){return null===this.map?e.$:this.map.get(e)??null}ho(e){let t=this.map;null!==t&&t.get(e.r)===e&&t.delete(e.r),e.Se(this.engine)}vt(){let e=this.engine,t=this.l.u,n=this.Ee;Ze=Te();let r=t.length,i=n.length,s=this.S,o=s.parentNode;if(0===r){if(i>0){ot(n[0].qe(),n[i-1].s);for(let e=0;e<i;e++)this.ho(n[e])}return void(this.Ee=[])}let l=new Array(r),a=0;for(;a<r&&a<i&&this.Rt(t[a])===n[a];)l[a]=n[a],a++;let u=i-1,c=r-1;for(;u>=a&&c>=a&&this.Rt(t[c])===n[u];)l[c]=n[u],u--,c--;for(let e=a;e<=u;e++){let t=n[e],r=t.r;r.y&&this.Rt(r)===t?t.fo=e:(t.uo(),this.ho(t))}if(a<=c){let n=c-a+1,u=new Int32Array(n),h=!1;if(i>0)for(let e=0;e<n;e++){let n=this.Rt(t[a+e]);null!==n&&n.y?(u[e]=n.fo,h=!0):u[e]=-1}let d=c+1<r?l[c+1].qe():s;if(h){let r=function(e){let t=e.length,n=new Uint8Array(t),r=new Int32Array(t).fill(-1),i=[];for(let n=0;n<t;n++){let t=e[n];if(t<0)continue;let s=0,o=i.length;for(;s<o;){let n=s+o>>1;e[i[n]]<t?s=n+1:o=n}s>0&&(r[n]=i[s-1]),i[s]=n}let s=i.length>0?i[i.length-1]:-1;for(;s>=0;)n[s]=1,s=r[s];return n}(u),i=d;for(let s=n-1;s>=0;s--){let n=t[a+s],u=this.Rt(n);null!==u&&u.y?0===r[s]&&u.insertBefore(o,i):(o.insertBefore(et(e,this.A,n,this),i),u=Ye()),l[a+s]=u,i=u.qe()}}else{let n=document.createDocumentFragment();for(let r=a;r<=c;r++)n.appendChild(et(e,this.A,t[r],this)),l[r]=Ye();o.insertBefore(n,d)}}this.Ee=l,Ke(o)}Se(){this.y=!1;let e=this.l;if(e.$===this)e.$=null;else if(null!==e.L){let t=e.L.indexOf(this);t>=0&&e.L.splice(t,1),0===e.L.length&&(e.L=null)}for(let e of this.Ee)e.Se(this.engine);this.map?.clear()}};function st(e,t,n){for(;n<t.length;n++){e=e.firstChild;for(let r=t[n];r>0;r--)e=e.nextSibling}return e}function ot(e,t){let n=document.createRange();n.setStartBefore(e),n.setEndAfter(t),n.deleteContents()}var lt=()=>ee.bindAttributeName;function at(){return{a:0,i:1,name:"",o:null,N:null,V:t,Nn:null,A:null,X:null,I:null,xt:null,ke:!1,H:null,z:null,ro:!1,$t:!1,Nt:!1,Et:null,ao:null,F:-1,Ze:!1,co:!1}}var ut=["state","element","auto","none"],ct=["call","connect"],ht="$command.";function dt(e,t,n){x.test(t)&&(null===n&&_(1401,[t,Number(t.slice(1))]),t=`${n.t}.*.${t}`);let r=e.o(function(e,t){return 46!==e.charCodeAt(0)?e:(null===t&&_(1402,[e]),"."===e?`${t.t}.*`:`${t.t}.*${e}`)}(t,n)),i=null===n?0:n.n+1;r.n>i&&_(1401,[r.t,r.n,i]);for(let e=1;e<=r.n;e++){let t=e===i?n:n.f[e];r.f[e]!==t&&_(1403,[r.t,r.f[e].t,t.t])}return c.go?.(e,r),r}var ft=e=>1===e.i&&("outerHTML"===e.name||"outerText"===e.name),pt=e=>8===e.i||ft(e)||1===e.i&&Fe(e.name);function mt(e){_(202,[e])}function gt(e,t,n,r,i){let s=se(t).map(t=>function(e,t,n,r,i){let s=function(e,t){let n=t.find(e=>e.startsWith("on")),r=null,i=null;for(let n of t){let t=n.indexOf("=");if(t<0)continue;e.Mt||_(31);let s=n.slice(0,t).trim(),o=n.slice(t+1).trim(),l="init"===s;!l&&"sync"!==s&&_(33,[s,n]),null!==(l?r:i)&&_(34,[s]),(l?ut:ct).includes(o)||_(35,[s,o]),l?r=o:i=o}return{ro:t.includes("ro"),$t:t.includes("prevent"),Nt:t.includes("stop"),event:n?n.slice(2):null,H:r,z:i}}(e,t.tn),o=r.localName.includes("-"),l=t.ve,a=t.Je;if("event"===t.w){if(null!==s.H&&"none"!==s.H&&_(36),"eventToken"===l[0])return{...at(),a:i,i:13,name:l.slice(1).join("."),Et:a,ke:o,$t:s.$t,Nt:s.Nt};let n=a.startsWith(ht)?a.slice(9):null,{$t:r,Nt:u}=s,c=t.be.slice(2),h=t.tn.includes("direct"),d=!h&&je.has(c);return d&&e.eo(c),{...at(),a:i,i:5,name:c,Ze:d,ke:o,co:h,Nn(t,i){r&&t.preventDefault(),u&&t.stopPropagation();try{if(null!==n)e.qo(n,t,i);else{let n=e.Ko(a,t,i);G(n)&&n.then(void 0,e=>console.error(e))}}catch(e){console.error(e)}}}}if("spread"===t.w)return{...at(),a:i,i:14,o:dt(e,a,n),ke:o};if("command"===l[0]&&l.length>1)return a.startsWith(ht)||_(1201,[t.be,a]),{...at(),a:i,i:12,name:l.slice(1).join("."),Et:a,ke:o};let u=dt(e,a,n),c={...at(),a:i,i:1,name:t.be,o:u,N:ke(t.Qe),I:ke(t.I),ro:s.ro,H:s.H,z:s.z};if("radio"===t.w||"checkbox"===t.w)return("element"===s.H||"auto"===s.H)&&_(37,[t.w,s.H]),c.i="radio"===t.w?9:10,s.ro||(c.xt=s.event??"input"),c;if(l.length>1){let e=l.slice(1).join("."),t=l[0];if("class"===t||"attr"===t||"style"===t)return c.H=null,c.name=e,"class"===t?(c.i=2,c.V=r.classList.contains(e)):c.i="attr"===t?"srcdoc"===e&&"iframe"===r.localName?1:3:4,c}return"html"===t.be?(c.i=8,c):(c.name="text"===t.be?"textContent":t.be,c.ke=o&&!Ee(c.name),!o&&!s.ro&&function(e,t){let n=e.localName;if("input"===n){let n=(e.getAttribute("type")||"text").toLowerCase();return"button"!==n&&(("radio"===n||"checkbox"===n)&&"checked"===t||"value"===t||"valueAsNumber"===t||"valueAsDate"===t)}return("select"===n||"textarea"===n)&&"value"===t}(r,c.name)&&(c.xt=s.event??("select"===r.localName?"change":"input")),c)}(e,t,n,r,i));for(let e=0;e<s.length;e++)14===s[e].i&&(s[e].ao=s.slice(e+1).filter(e=>1===e.i).map(e=>e.name));return s}var yt=/\{\{([\s\S]+?)\}\}/g;function bt(e){let t=e.data,n=[],r=0;yt.lastIndex=0;for(let i=yt.exec(t);null!==i;i=yt.exec(t)){let s=yt.lastIndex-i[0].length;s>r&&e.before(t.slice(r,s));let o=e.ownerDocument.createTextNode("");e.before(o),n.push({a:o,Qo:i[1].trim()}),r=yt.lastIndex}return 0===n.length||(r<t.length&&e.before(t.slice(r)),e.remove()),n}function vt(e,t,n,r){let i=function(e){return{be:"textContent",ve:["textContent"],tn:[],I:[],...W(e),w:"text"}}(t);return{...at(),a:r,i:0,o:dt(e,i.Je,n),N:ke(i.Qe),V:""}}function wt(e){let t=e.getAttribute(lt());if(null===t)return null;let n=se(t)[0];return void 0===n||"for"!==n.w&&"if"!==n.w&&"elseif"!==n.w&&"else"!==n.w?null:n}var _t=(e,t)=>0===e?ee.commentIfPrefix:null===t.o?ee.commentElsePrefix:ee.commentElseIfPrefix;function $t(e,t,n){let r=(t,r)=>({el:t,o:"else"===r.w?null:dt(e,r.Je,n),N:"else"===r.w?null:ke(r.Qe)}),i=[r(t,wt(t))];for(let e=t.nextSibling;null!==e;e=e.nextSibling){if(3===e.nodeType&&""===e.data.trim()||8===e.nodeType)continue;if(1!==e.nodeType||"template"!==e.localName)break;let t=wt(e);if(null===t||"elseif"!==t.w&&"else"!==t.w||(i.push(r(e,t)),"else"===t.w))break}return i}var kt=new WeakSet;function St(e,t,n,r,i,s,o,l){let a=(t,n)=>{let i=document.createComment(n);return t.replaceWith(i),r&&c.An?.(e,i,t),i},u=t=>{for(let h=0;h<t.length;h++){let d=t[h];if(null!==d.parentNode)if(1===d.nodeType){let t=d,l=t.localName;if(r){if("script"===l||"style"===l||kt.has(t))continue;if(kt.add(t),l===ee.tagNames.state){u([...t.childNodes]);continue}}let h="template"===l?wt(t):null;if(null!==h){if("for"===h.w){let r=dt(e,h.Je,n),s=At(e,t,r,!0);i(a(t,ee.commentForPrefix),r,s)}else"if"===h.w?s($t(e,t,n).map((t,r)=>({A:At(e,t.el,n,!1),o:t.o,N:t.N,S:a(t.el,_t(r,t))}))):mt(h.w);continue}let f=t.getAttribute(lt()),p=null===f?null:gt(e,f,n,t,0),m="noscript"!==l&&"iframe"!==l&&!p?.some(pt)&&!c.yo?.(t);try{r&&m&&u([...t.childNodes])}finally{null!==p&&o(t,p)}!r&&m&&u([...t.childNodes])}else if(3===d.nodeType&&e.Bt&&d.data.includes("{{")&&!kt.has(d))for(let{a:e,Qo:t}of bt(d))l(e,t);else if(8===d.nodeType){let e=Nt.exec(d.data),t=e&&d.parentNode.localName;if(null!==t&&"textarea"!==t&&"title"!==t){let t=document.createTextNode("");d.replaceWith(t),l(t,e[1])}}}};u(t)}var Nt=/^\s*@@\s*(?:wcs-text)?\s*:\s*([\s\S]+?)\s*$/,Et=e=>{let t=document.createRange();return t.selectNodeContents(e),e.content??t.cloneContents()};function At(e,t,n,r){let i=document.importNode(Et(t),!0),s=[],o=[],l=e=>s.push(e)-1;St(e,[...i.childNodes],n,!1,(e,t,n)=>{o.push({...at(),a:l(e),i:6,o:t,A:n})},e=>{let t=e.map(e=>({a:l(e.S),A:e.A,o:e.o,N:e.N}));o.push({...at(),a:t[0].a,i:7,X:t})},(e,t)=>{let n=l(e);for(let e of t)ft(e)&&_(203,[e.name]),e.a=n;o.push(...t),e.removeAttribute(lt())},(t,r)=>{o.push(vt(e,r,n,l(t)))}),Pt(i,new Set(s),!0);let a=s.map(e=>function(e,t){let n=[];for(let r=t;r!==e;r=r.parentNode){let e=0;for(let t=r.previousSibling;null!==t;t=t.previousSibling)e++;n.unshift(e)}return n}(i,e)),u=1===i.childNodes.length&&8!==i.firstChild.nodeType,c=o.some(e=>6===e.i||7===e.i),h=[],d=new Set,f=[],p=[],m=r?n.n+1:-1;for(let e of o){if(5===e.i&&e.Ze&&!e.ke&&!Ct(s[e.a],i)){f.push(e);continue}p.push(e);let t=e.o;if(null!==t&&t.n===m&&t.f[m]===n&&xt(e)&&(e.F=h.push(e)-1),7===e.i)for(let t of e.X)d.add(t.a);else d.add(e.a)}let g=[...d].sort((e,t)=>e-t);return{on:i,root:u?i.firstChild:null,Rn:a,build:g,Ne:f,Yo:p,Tn:u,Go:c,mo:[],Ke:h}}function Ct(e,t){for(;e.parentNode!==t;e=e.parentNode){if(e.parentNode.localName.includes("-"))return!0;for(let t=e.previousSibling;t;t=t.previousSibling)if(8===t.nodeType)return!0}return!1}function xt(e){if(null!==e.H)return!1;switch(e.i){case 0:case 2:case 3:case 4:case 8:return!0;case 1:return!e.ke&&null===e.xt;default:return!1}}var Tt=new Set(["table","thead","tbody","tfoot","tr","colgroup","select","optgroup","datalist"]);function Pt(e,t,n){for(let r=e.firstChild;null!==r;){let e=r.nextSibling;3===r.nodeType?n&&!t.has(r)&&""===r.data.trim()&&r.remove():1===r.nodeType&&Pt(r,t,Tt.has(r.localName)),r=e}}var Ot=new WeakMap;function Lt(e,t){let n=9===t.nodeType?t.body:t;e.root=t,Ot.set(t,e),It(e,[...n.childNodes]),e.He()}function Mt(e,t,n){try{let r="template"===t.localName?wt(t):null;null!==r&&!n&&_(204,[r.w]),It(e,[t])}catch(e){console.error(e)}e.He()}function It(e,t){St(e,t,null,!0,(t,n,r)=>{new it(e,r,Je(e,n,null,t),t).vt()},t=>{nt(e,t,null,null)},(t,n)=>{c.An?.(e,t,n);for(let r of n)tt(e,r,t,null,null)},(t,n)=>{c.An?.(e,t,n),tt(e,vt(e,n,null,0),t,null,null)})}var jt=Symbol.for("wcstack.binder"),Rt=Symbol.for("wcstack.binder.pending"),Ht=Symbol.for("wcstack.binder.taken"),Wt=new Map;function zt(e,t){if(1!==e.nodeType||!e.isConnected)return;let n=Ot.get(e.getRootNode());void 0===n||!1===n.element?.isConnected?Wt.set(e,t):Mt(n,e,t?.range)}function Dt(){let e=[...Wt];Wt.clear();for(let[t,n]of e)zt(t,n);!function(){let e=function(){let e=globalThis[jt];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}();if(null===e)return;let t=function(){let e=globalThis,t=e[Rt];return void 0===t&&(t=[],e[Rt]=t),t}();if(0===t.length)return;let n=t.splice(0,t.length),r=function(){let e=globalThis,t=e[Ht];return void 0===t&&(t=new WeakSet,e[Ht]=t),t}();for(let t of n)r.add(t),e.bind(t)}()}var Ut=class{constructor(){this.name="dirty",this.rt=(e,r)=>{if(0===e.n){let r=e.J;return r!==t&&r!==n&&(e.J=n,!0)}let i=null===r?null:r.dt;if(null===i)return!1;let s=i[e.F];return s!==t&&s!==n&&(i[e.F]=n,!0)}}Ho(e,t,n){null!==t.getter&&this.rt(t,n),e.bt(t,n),e.vn(t,n,this.rt)}Lo(e,t){let n=t.l.o.At;if(null!==n)for(let r of n)r.n===t.l.n?e.nt(r,t,this.rt):e.Jt(t,r,t=>e.nt(r,t,this.rt))}me(e,t,n){this.rt(t,n),c.ye?.(e,t,n),e.bt(t,n),e.vn(t,n,this.rt)}Bo(e,i,s){let o=0===i.n;if(!o&&null===s)return;let l=o?null:s.dt??=new Array(e.Oe).fill(t),a=null===l?i.J:l[i.F];if(a!==t&&a!==n&&a!==r&&(null===l||i.F in l))return a;a=r;try{return a=e.Do(i,null===l?null:s)}finally{null===l?i.J=a:l[i.F]=a}}Kt(e){e.dt=null}mt(e){for(let t of e.B.all())null!==t.getter&&(0===t.n?t.J===n&&(t.J=r):e.Zt(t.f[t.n],e=>{let i=e.dt;null!==i&&i[t.F]===n&&(i[t.F]=r)}))}},Ft=0,qt=new WeakMap;function Bt(e,t=e.getRootNode()){qt.set(t,[...qt.get(t)??[],e].filter((e,t,n)=>e.isConnected&&n.lastIndexOf(e)===t))}function Kt(e){let t=qt.get(e)??[],n=t.filter(t=>t.getRootNode()===e);return Promise.any(n.map(e=>e.initializePromise.then(()=>e._||e.connectedCallbackPromise))).then(()=>{},r=>n.length?qt.get(e)!==t?Kt(e):Promise.reject(r.errors[0]):void 0)}var Gt=typeof HTMLElement>"u"?class{}:HTMLElement,Vt=class extends Gt{constructor(){super(),this.engine=null,this.Fn=!1,this.Ve=!1,this.V=null,this.ze=null,this.loaded=!1,this.ln=null,this.connectedCallbackPromise=new Promise((e,t)=>{this.sn=e,this.wo=t}),this.connectedCallbackPromise.catch(()=>{}),this.initializePromise=new Promise(e=>{this.rn=e})}static{this.getBindingsReady=Kt}static{this.hasConnectedCallbackPromise=!0}connectedCallback(){if(this.Fn){if(null!==this.ze)return void this.ze.Xe();Bt(this);let e=this.engine;if(null!==e){let t=e.root;t===this.getRootNode()&&!Ot.has(t)&&Ot.set(t,e),Dt(),c.element?.(e,"back"),this.bo("$connectedCallback",50,()=>{this.isConnected&&c.element?.(e,"connected")})}return}this.Fn=!0;let e=this.getRootNode(),t=c.it?.(this,e);if(t)return this.ze=t,!t.vo&&this.parentNode instanceof ShadowRoot&&Bt(this),void(void 0===t.Lt?this.ko():t.Lt()).then(e=>(this.loaded=!0,t.start(e,()=>this.So()))).then(()=>{this.rn(),this.sn()},e=>this.kt(e,t.vo));this.start(e),Bt(this)}disconnectedCallback(){if(null!==this.ze)return void this.ze.On();let e=this.engine;if(null===e)return;let t=e.root;Ot.get(t)===e&&Ot.delete(t),Bt(this,t),this.bo("$disconnectedCallback",51),c.element?.(e,"disconnected")}setInitialState(e){if(this.Ve&&_(14),this.loaded)this.ze.reset(e);else if(null===this.engine)if(null!==this.ln){let t=this.ln;this.ln=null,t(e)}else this.V=e;else this.engine.reset(e)}createState(e,t){let n=this.engine;null===n&&_(15),"readonly"===e&&n.Ce++;try{t(n.proxy)}finally{"readonly"===e&&n.Ce--}}async createStateAsync(e,t){let n=this.engine;null===n&&_(15),await t("writable"===e?n.proxy:new Proxy(n.proxy,{get(e,t,n){let r=Reflect.get(e,t,n);return"$setAll"===t||"$resolve"===t?(...e)=>(e.length>2&&_(8),r(...e)):r},set(){_(8)}}))}async ko(){await 0;let e=this.getAttribute("state");if(null!==e){let t=t=>[...t.querySelectorAll('script[type="application/json"]')].find(t=>t.id===e),n=t(this.getRootNode())??t(document);return void 0===n?Promise.reject(new Error(`[@wcstack/state] ${w(16,[e])}`)):Promise.resolve(JSON.parse(n.textContent||"{}"))}let t=this.getAttribute("src");if(null!==t)return async function(e){let t=new URL(e,document.baseURI).href;if(/\.json(?:[?#]|$)/.test(t)){let n=await fetch(t);return n.ok||_(13,[e,n.status]),await n.json()}return(await(import(t))).default??{}}(t);let n=this.getAttribute("json");if(null!==n)return Promise.resolve(JSON.parse(n));let r=this.querySelector('script[type="module"]');return null!==r?async function(e){let t=!1,n=e=>{e.effectiveDirective.startsWith("script-src")&&(t=!0)};document.addEventListener("securitypolicyviolation",n);let r="function"==typeof URL.createObjectURL,i=r?URL.createObjectURL(new Blob([e.text],{type:"application/javascript"})):"data:text/javascript;charset=utf-8,"+encodeURIComponent(`${e.text}\n//${++Ft}`);try{return(await(import(i))).default??{}}catch(e){throw await new Promise(e=>setTimeout(e)),new Error(`[@wcstack/state] ${t?w(42):w(43,[e instanceof Error?e.message:String(e)])}`,{cause:e})}finally{document.removeEventListener("securitypolicyviolation",n),r&&URL.revokeObjectURL(i)}}(r):null!==this.V?Promise.resolve(this.V):new Promise(e=>{this.ln=e})}async start(e){try{let t=e.host;(this.hasAttribute("mount")||this.hasAttribute("bind-component")||t?.hasAttribute("data-wc-definition"))&&b("scopes","<wcs-state>");let n=await this.ko(),r=y(n);if(r&&await r,this.getRootNode()!==e)return this.V=n,this.Fn=!1,void(this.isConnected&&this.connectedCallback());this.hasAttribute("enable-ssr")&&b("ssr","enable-ssr");let i=Ot.get(e)?.element;i?.isConnected&&(i._||i.ze)&&_(47);let s=new Z(n,new Ut);s.element=this,this.engine=s,c.element?.(s,"mounting"),Lt(s,e),Dt(),s.bn(),this.So(),await s.we("$connectedCallback"),this.isConnected&&c.element?.(s,"connected"),this.sn()}catch(e){this.Ve=!this._,this.kt(e)}}So(){this._=!0,this.rn()}kt(e,t){this.He(this._?50:49,e),this.rn(),t?this.sn():this.wo(e)}He(e,t){let n=["mount","bind-component","state","src"].flatMap(e=>this.hasAttribute(e)?[e,this.getAttribute(e)]:[]);console.error(`[@wcstack/state] ${w(e,[this.localName,...n])}`,t)}bo(e,t,n){(async()=>this.engine.we(e))().then(n,e=>this.He(t,e))}},Jt=[];function Qt(){return(Jt=Jt.filter(e=>e.deref())).map(e=>e.deref())}var Xt,Yt=e=>t=>{let n=e(t);return e=>null==e?e:n(e)},Zt="en";function en(){if(ee.locale!==Xt){Xt=ee.locale;try{Zt=Intl.getCanonicalLocales(Xt)[0]}catch{console.warn(`[@wcstack/state] ${w(48,[Xt])}`),Zt="en"}}return Zt}var{eq:tn,ne:nn,not:rn,lt:sn,le:on,gt:ln,ge:an,falsy:un,truthy:cn,boolean:hn}=we,dn={toFixed:{factory:e=>{let t=ge(e?.[0]??"0","toFixed");return e=>("number"!=typeof e&&fe("toFixed"),e.toFixed(t))},arity:[0,1]},locale:{factory:e=>{let t=e?.[0];return e=>("number"!=typeof e&&fe("locale"),e.toLocaleString(t??en()))},arity:[0,1]},upper:{factory:Yt(()=>e=>String(e).toUpperCase()),arity:[0,0]},lower:{factory:Yt(()=>e=>String(e).toLowerCase()),arity:[0,0]},capitalize:{factory:Yt(()=>e=>{let t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)}),arity:[0,0]},trim:{factory:Yt(()=>e=>String(e).trim()),arity:[0,0]},slice:{factory:Yt(e=>{let t=[ye(e,0,"slice")],n=e?.[1];return typeof n<"u"&&t.push(ge(n,"slice")),e=>String(e).slice(...t)}),arity:[1,2]},padStart:{factory:Yt(e=>{let t=ye(e,0,"padStart"),n=e?.[1]??"0";return e=>String(e).padStart(t,n)}),arity:[1,2]},padEnd:{factory:Yt(e=>{let t=ye(e,0,"padEnd"),n=e?.[1]??" ";return e=>String(e).padEnd(t,n)}),arity:[1,2]},repeat:{factory:Yt(e=>{let t=ye(e,0,"repeat");return e=>String(e).repeat(t)}),arity:[1,1]},reverse:{factory:Yt(()=>e=>String(e).split("").reverse().join("")),arity:[0,0]},truncate:{factory:Yt(e=>{let t=ye(e,0,"truncate"),n=e?.[1]??"…";return e=>{let r=String(e);return r.length<=t?r:r.slice(0,t)+n}}),arity:[1,2]},join:{factory:e=>{let t=e?.[0]??", ";return e=>(Array.isArray(e)||_(30,["join"]),e.join(t))},arity:[0,1]},round:{factory:e=>{let t=Math.pow(10,ge(e?.[0]??"0","round"));return e=>("number"!=typeof e&&fe("round"),Math.round(e*t)/t)},arity:[0,1]},floor:{factory:e=>{let t=Math.pow(10,ge(e?.[0]??"0","floor"));return e=>("number"!=typeof e&&fe("floor"),Math.floor(e*t)/t)},arity:[0,1]},ceil:{factory:e=>{let t=Math.pow(10,ge(e?.[0]??"0","ceil"));return e=>("number"!=typeof e&&fe("ceil"),Math.ceil(e*t)/t)},arity:[0,1]},percent:{factory:e=>{let t=ge(e?.[0]??"0","percent");return e=>("number"!=typeof e&&fe("percent"),`${(100*e).toFixed(t)}%`)},arity:[0,1]},unit:{factory:Yt(e=>{let t=e?.[0]??he("unit");return e=>String(e)+t}),arity:[1,1]},date:{factory:e=>{let t=e?.[0];return e=>(e instanceof Date||pe("date"),e.toLocaleDateString(t??en()))},arity:[0,1]},time:{factory:e=>{let t=e?.[0];return e=>(e instanceof Date||pe("time"),e.toLocaleTimeString(t??en()))},arity:[0,1]},datetime:{factory:e=>{let t=e?.[0];return e=>(e instanceof Date||pe("datetime"),e.toLocaleString(t??en()))},arity:[0,1]},ymd:{factory:e=>{let t=e?.[0]??"-";return e=>{e instanceof Date||pe("ymd");let n=e.getFullYear().toString(),r=(e.getMonth()+1).toString().padStart(2,"0"),i=e.getDate().toString().padStart(2,"0");return`${n}${t}${r}${t}${i}`}},arity:[0,1]},hms:{factory:e=>{let t=e?.[0]??":";return e=>{e instanceof Date||pe("hms");let n=e.getHours().toString().padStart(2,"0"),r=e.getMinutes().toString().padStart(2,"0"),i=e.getSeconds().toString().padStart(2,"0");return`${n}${t}${r}${t}${i}`}},arity:[0,1]},eq:tn,ne:nn,not:rn,lt:sn,le:on,gt:ln,ge:an,add:ve("add",(e,t)=>e+t),sub:ve("sub",(e,t)=>e-t),mul:ve("mul",(e,t)=>e*t),div:ve("div",(e,t)=>e/t),mod:ve("mod",(e,t)=>e%t),abs:{factory:()=>e=>("number"!=typeof e&&fe("abs"),Math.abs(e)),arity:[0,0]},clamp:{factory:e=>{let t=ye(e,0,"clamp"),n=ye(e,1,"clamp");return e=>("number"!=typeof e&&fe("clamp"),Math.min(Math.max(e,t),n))},arity:[2,2]},int:{factory:()=>e=>parseInt(String(e),10),arity:[0,0]},float:{factory:()=>e=>parseFloat(String(e)),arity:[0,0]},falsy:un,truthy:cn,defaults:{factory:(e,t)=>{let n=be(e?.[0]??he("defaults"),t);return e=>e||n},arity:[1,1]},coalesce:{factory:(e,t)=>{let n=be(e?.[0]??he("coalesce"),t);return e=>e??n},arity:[1,1]},boolean:hn,number:{factory:()=>e=>Number(e),arity:[0,0]},string:{factory:()=>e=>String(e),arity:[0,0]},nullIfEmpty:{factory:()=>e=>""===e?null:e,arity:[0,0]}},fn=!1,pn={name:"formats",install:function(){fn||(fn=!0,ue(dn))}};function mn(e,t,n){if(Math.abs(e.length-t.length)>n)return n+1;let r=new Array(t.length+1),i=new Array(t.length+1);for(let e=0;e<=t.length;e++)r[e]=e;for(let n=1;n<=e.length;n++){i[0]=n;for(let s=1;s<=t.length;s++){let o=e[n-1]===t[s-1]?0:1;i[s]=Math.min(r[s]+1,i[s-1]+1,r[s-1]+o)}for(let e=0;e<=t.length;e++)r[e]=i[e]}return r[t.length]}function gn(e,t){if(0===e.length)return"";let n=e.toLowerCase(),r=null,i=3;for(let e of t){let t=mn(n,e.toLowerCase(),2);t<i&&(r=e,i=t)}return null!==r?` Did you mean "${r}"?`:""}var yn=" Validate statically: npx @wcstack/lint <file>.",bn=["","binding-syntax","template-syntax","binding-path-missing","binding-type-expectation","filter-unknown","filter-arity","getter-cycle","getter-depth-exceeded","index-arity","index-param-range","recursion-unsupported","token-misconfigured","token-undeclared","wildcard-rank","spread-no-bindable","declaration-alias","name-alias"],vn=e=>{let t=bn[e/100|0];return t?`[wcs/${t}] `:""},wn=["enableMustache","sameValueGuard","enableDirectionalInitialSync"],_n=(e,t)=>`<${e}${t.map((e,t)=>t%2?`="${e}"`:` ${e}`).join("")}>`,$n="https://github.com/wcstack/wcstack/blob/main/docs/csp.md",kn={1:()=>"$scan was removed (use $watch or $on)",2:e=>`"${e}" is a getter without a setter`,3:e=>`no row for "${e}"`,4:(e,t)=>`cannot write "${e}": its parent is ${t}`,5:e=>`"${e}" is not a method`,6:e=>`$getAll("${e}"): no loop level in common with the context`,7:e=>`$eqIndex("${e}") needs a list row scope.`,8:()=>"This state is readonly.",9:e=>`$setAll("${e}") needs indexes ([] for every match)`,10:(e,t)=>`$setAll("${e}", …, { spread: true }) needs an array of ${t} values`,11:()=>"updates did not settle after 32 passes",41:()=>"render chain depth limit exceeded (100 drains that rendering itself started); bindings for this batch were not applied.",12:(e,t)=>`binding "${e}: ${t}" failed to apply.`,13:(e,t)=>`failed to load "${e}": ${t}`,14:()=>"this <wcs-state> failed to initialize; create a new one",15:()=>"state is not initialized",16:e=>`no <script> with id "${e}"`,42:()=>`The inline <script> of <wcs-state> was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/state, or allow blob: in script-src. Moving the state into an external file (src="./state.js") needs neither. See ${$n}`,43:e=>`Failed to evaluate the inline <script> of <wcs-state>: ${e}. If this page sets a Content-Security-Policy, see ${$n}`,17:e=>`a subscriber of token "${e}" threw.`,18:e=>`${e} must be an array of strings.`,19:e=>`${e} entries must be non-empty strings.`,20:(e,t,n)=>`${e} entry "${t}" conflicts with the reserved namespace name "${n}".`,21:(e,t)=>`${e} entry "${t}" is duplicated.`,22:()=>"$on must be an object of handlers.",23:e=>`$on entry "${e}" is not declared in $eventTokens.`,24:e=>`$on entry "${e}" must be a function.`,25:e=>`view-transition naming-limit (${e}) reached.`,26:e=>`filter ${e} requires at least one option`,27:e=>`filter ${e} requires a number as option`,28:e=>`filter ${e} requires a number value`,29:e=>`filter ${e} requires a date value`,30:e=>`filter ${e} requires an array value`,31:()=>"init=/sync= modifiers require enableDirectionalInitialSync.",33:(e,t)=>`Unknown binding modifier "${e}" in "${t}".`,34:e=>`Binding modifier "${e}" may only be specified once.`,35:(e,t)=>`Invalid ${e} modifier value "${t}".`,36:()=>"Event bindings only allow init=none.",37:(e,t)=>`Binding type "${e}" does not support init=${t}.`,38:e=>`Property "${e}" is not declared by wcBindable.`,39:(e,t)=>`init=${e} is incompatible with wcBindable member "${t}".`,40:e=>`sync=connect requires observable property "${e}".`,44:(e,t)=>`${e}: "${t}" is not one of its options, or not of the option's type.${"bootstrapState"===e&&wn.includes(t)?" 4.0 moved it to the state's $behavior.":""}`,45:()=>"a re-set state may not change $behavior: create the element again.",47:()=>'a second <wcs-state> on the same root: there is one state tree per root — graft a subtree with <wcs-state mount="path"> (v1\'s name="…" is gone: read the mounted state by its path).',48:e=>`the locale "${e}" (<html lang> or bootstrapState's locale) is not a language tag Intl takes (en-US, not en_US): the locale filters use "en".`,46:()=>'$features must be an array of add-on names (["temporal", "formats"]).',49:(e,...t)=>`${_n(e,t)} failed to initialize.`,50:(e,...t)=>`${_n(e,t)} $connectedCallback failed.`,51:(e,...t)=>`${_n(e,t)} $disconnectedCallback failed.`,101:e=>`Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.`,102:(e,t)=>`"${e}": "${t}" takes no modifiers or filters on its left side — write "${t}:".`,103:e=>`"${e}": "else" takes no value — write "else:".`,104:e=>`Invalid spread binding "${e}": spread target path is required.`,105:e=>`Invalid spread binding "${e}": filters are not allowed on spread targets.`,106:e=>`"${e}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (class, attr, style, command, eventToken, state).`,107:(e,t)=>`unterminated ${e} quote in the filter arguments "(${t})". Close the quote.`,108:e=>`Invalid filter format: missing closing parenthesis in "${e}".`,109:e=>`Invalid filter format: missing opening parenthesis in "${e}".`,110:e=>`Invalid filter format: ")" comes before "(" in "${e}".`,111:(e,t)=>`"${e}": unexpected "${t}" after the filter's closing ")" — separate filters with "|" (write "${e.slice(0,e.lastIndexOf(")")+1)}|${t}").`,112:e=>`an empty filter in "${e}" — remove the extra "|" or name the filter.`,113:(e,t)=>`"${e}" is not a filter name: a modifier list "#${t}" comes before the input filters, not inside one`,114:e=>`"${e}" is not a filter name: "#" cannot appear in one.`,115:e=>`"${e}": a binding takes one modifier list after a single "#"`,116:e=>`"${e}": the left side of a binding must name a property — write "<property>: <path>" (modifiers and input filters come after the name).`,117:(e,t)=>`"${e}" has ${t} path segments — the limit is 512.`,32:e=>`"${e}": 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.`,120:e=>`"${e}": a state path cannot go through "__proto__" or "prototype" (it would reach every object's prototype).`,121:e=>`"${e}": "for:" takes no filters — a row is "<path>.<index>", so the rows of a filtered list would name other elements. Declare a getter that returns the filtered list and loop over it ("for: <getter>").`,119:e=>`"${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).`,201:e=>`Invalid bindText: "${e}". 'if', 'elseif', 'else', and 'for' bindings must be single binding.`,202:e=>`"${e}:" must follow an "if:" template`,204:e=>`a "${e}:" template at the top of inserted content was not rendered, as it would render beside itself out of the inserter's reach: wrap it in an element.`,203:e=>`"${e}:" replaces its element, so it cannot be used inside a "for" / "if" template (a row or branch keeps its nodes by position): bind innerHTML: on a wrapper element instead.`,301:e=>`Path "${e}" does not exist on the state tree.`,401:(e,t)=>`class.${e} needs a boolean, got ${t}.`,501:e=>`filter not found: ${e}.`,601:(e,t,n)=>`filter "${e}" requires at least ${t} argument(s) (${n} given).`,602:(e,t,n)=>`filter "${e}" accepts at most ${t} argument(s) (${n} given).`,701:e=>`"${e}" depends on itself`,801:e=>`"${e}"`,901:(e,t,n,r)=>`${e}("${t}") takes ${n} index(es), got ${r}.`,902:(e,t,n,r)=>`${e}("${t}") takes at most ${n} index(es), got ${r}.`,1001:e=>`"${e}": list index parameters run from $1 to $128.`,1101:e=>`"${e}" uses "**", which is not accepted here.`,1201:(e,t)=>`"${e}: ${t}": the right-hand side must be $command.<name>`,1202:(e,t)=>`<${e}> declares no static wcBindable (${t}).`,1203:(e,t)=>`<${e}> declares no command "${t}".`,1204:(e,t)=>`<${e}> declares no property "${t}".`,1301:e=>`eventToken "${e}" is not declared in $eventTokens.`,1302:e=>`"$command.${e}" is not declared in $commandTokens.`,1401:(e,t,n=0)=>`"${e}" needs ${t} enclosing loop level(s); the scope provides ${n}.`,1402:e=>`"${e}" is relative: it needs an enclosing "for" template`,1403:(e,t,n)=>`"${e}" ranges over the rows of "${t}", but the enclosing "for" template at that level renders "${n}".`,1501:(e,t)=>`<${e}> declares no static wcBindable (${t}).`,1601:(e,t)=>`${e} was removed: write ${t}.`,1701:(e,t)=>`${e} was removed: write ${t}.`};function Sn(e,t){let n=kn[e];return void 0===n?`${vn(e)}#${e} ${t.join(" ")}`:vn(e)+n(...t)}var Nn=new Set(["binding-syntax","template-syntax","filter-unknown","filter-arity","index-arity","wildcard-rank","token-undeclared","binding-path-missing","index-param-range"]),En=[[/no loop level in common with the context/,"; pass indexes ([] for all)."],[/"([^"#]+)#([^"]*)" is not a filter name: a modifier list .* comes before the input filters/,' — write "<property>#$2|$1".'],[/\[wcs\/recursion-unsupported\]/," 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."],[/must be single binding/,' Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).'],[/\[wcs\/wildcard-rank\] .* needs \d+ enclosing/,' Wrap it in that many "for" templates, or use $resolve(path, indexes) to name the row explicitly.'],[/\[wcs\/wildcard-rank\] .* ranges over the rows of/,' A "*" in a binding is the row of the loop around it: read a row of another list in a getter, with $resolve(path, indexes).'],[/\[wcs\/binding-type-expectation\] class\.([^ ]+)/,' Write "class.$1: path|truthy" to toggle on truthiness.'],[/path segments — the limit/," Every prefix of a path is interned, so the cost grows with the square of the depth."],[/\[wcs\/index-arity\] \$resolve/,' $resolve takes one index per "*"; $getAll / $setAll take at most that many (fewer expands the rest).'],[/"([^"#]+)#[^"]*" is not a filter name: "#" cannot appear in one/,' Modifiers belong on the left side of the binding, before the ":" — write "$1" here.']],An={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function Cn(e,t,n){let r=(void 0!==t&&e.includes("[wcs/filter-unknown]")?function(e){if("substr"===e)return' "substr" was removed in 4.0 — write slice(start, start + length): slice takes the end index, not a length.';let t=Object.hasOwn(An,e)?An[e]:null;return null===t?null:` "${e}" was renamed "${t}" in 3.2 and removed in 4.0 — write "${t}".`}(t):null)??(void 0!==t&&void 0!==n?gn(t,n):"");for(let[t,n]of En){let i=t.exec(e);null!==i&&(r+=n.replace(/\$(\d)/g,(e,t)=>i[Number(t)]))}let i=/"([^"#]+)#([^"]+)": a binding takes one modifier list/.exec(e);null!==i&&(r+=` — write "${i[1]}#${i[2].split("#").join(",")}".`),e.includes("[wcs/filter-unknown]")&&(e.includes("formats add-on")?r+=' On a split auto page: features="formats" on the root, or "$features": ["formats"].':oe.some(ce)||(r+=' No formatting filters are installed — add the formats add-on: installFeatures([formats]) from "@wcstack/state/features/formats" (a split auto page: features="formats", or "$features").'));let s=/\[wcs\/([\w-]+)\]/.exec(e);return null!==s&&Nn.has(s[1])&&!/ path segments — the limit is |inserted content was not rendered|formats add-on/.test(e)&&(r+=yn),r}var xn=new WeakMap,Tn=new WeakMap,Pn=new WeakSet,On=new WeakSet;function Ln(e,t){for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e}}function Mn(e){let t=new Set;for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n))for(let e of Object.getOwnPropertyNames(n))"$"!==e[0]&&"constructor"!==e&&t.add(e);return[...t]}function In(e,t){let n=[];for(let e=t;null!==e;e=e.d)n.unshift(e);let r=e.target,i=t=>null===t?null:function(e,t){let n=t.t.split("."),r=n.findIndex((e,t)=>t>0&&/^\d/.test(e));return r<0||n.indexOf("*",r)>=0||void 0!==Ln(e.target,t.t)?.get?t:e.B.Ct(o(t.t).o)}(e,t);for(let t of n){if(null!=i(t)?.getter||null===r||"object"!=typeof r)return null;if("*"===t.s){if(!Array.isArray(r)||0===r.length)return null;r=r[0];continue}if(Array.isArray(r)&&/^\d+$/.test(t.s)){if(Number(t.s)>=r.length)return null;r=r[Number(t.s)];continue}let n=Ln(r,t.s);if(void 0===n&&null===t.d&&e.mt.has(t.s))return null;if(void 0===n){let n=Mn(r),s=i(t.d);for(let t of e.B.all())t.d===s&&null!==t.getter&&n.push(t.s);return{seg:t.s,names:n}}if(void 0!==n.get||void 0!==n.set)return null;r=n.value}return null}function jn(e){Pn.has(e)||(Pn.add(e),setTimeout(()=>function(e){Pn.delete(e);let t=xn.get(e);if(void 0===t)return;let n=Tn.get(e);void 0===n&&Tn.set(e,n=new Set);for(let[r,i]of t){if(n.has(r))continue;n.add(r);let t=In(e,r);if(null===t)continue;let s=[...e.root?.querySelectorAll(`${ee.tagNames.state}[mount]`)??[]].find(e=>!On.has(e)&&(r.t+".").startsWith(e.getAttribute("mount")+"."));if(void 0!==s){n.delete(r),s.initializePromise.then(()=>{On.add(s),jn(e)});continue}let[l,a]=i?["watch-path-missing","$watch path"]:["binding-path-missing","Bound path"];c.ot?.(e,{type:"state:path-unresolved",source:i?"watch":"binding",path:r.t,missingSegment:t.seg});let u=e.B.Ct(o(r.t).o),h="";if(void 0!==u&&u!==r&&null!==u.getter){let e=u.f.slice(1).map((e,t)=>`for: ${0===t?e.t:e.t.slice(u.f[t].t.length+2)}`);h=` The getter "${u.t}" is declared for the rows of ${e.join(" → ")}; a list named by an index has rows of its own.`}console.warn(`[@wcstack/state] [wcs/${l}] ${a} "${r.t}" does not resolve on the state tree: "${t.seg}" is not declared.${gn(t.seg,t.names)}${h} Updates to this path will be silently dropped.${yn}`)}}(e),0))}function Rn(e,t,n=!1){if("$"===t.t[0]||t.t.includes("#")||!n&&null===t.d)return;let r=xn.get(e);void 0===r&&xn.set(e,r=new Map),r.has(t)||r.set(t,n),jn(e)}var Hn=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Wn=!1;function zn(e,t,n){let r="html"===n.name?"innerHTML":n.name;if(Wn||!(t instanceof TypeError)||!Ee(r)||!("trustedTypes"in globalThis))return;Wn=!0;let i="function"==typeof Ne()?.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 "${r}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${i}\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:n.a,property:r})}var Dn=new WeakMap;function Un(e,t,n){let r=e[t],i=void 0===n?void 0===r?null:`the event carried no detail (undefined) while element.${t} is ${typeof r}`:null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,t)||null!==r&&"object"==typeof r?null:`the event's detail is an object with a "${t}" key while element.${t} is ${typeof r}`;if(null===i)return;let s=Dn.get(e);void 0===s&&Dn.set(e,s=new Set),!s.has(t)&&(s.add(t),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${e.localName}> "${t}": ${i}. 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.`))}var Fn=[["$streams","$stream"],["$updatedCallback","$renderedCallback"]],qn={$trackDependency:"$dependOn",$untrackDependency:"$untracked"},Bn={name:"diagnostics",install(){c.Ao=Cn,c.Fo=Sn,c.go=Rn,c.detail=Un,c.Ve=h(c.Ve,zn);let e=c.se;c.se=(t,n)=>{(function(e){void 0!==e.$scan&&_(1);for(let[t,n]of Fn)void 0!==e[t]&&_(1601,[t,n])})(n),e?.(t,n),function(e){let t=e.$recursion;if(null===t||"object"!=typeof t)return;let n=Object.entries(t);if(1!==n.length||"string"!=typeof n[0][1])return;let[r,i]=n[0];if(!r.endsWith(".*")||!i.endsWith(".*"))return;let s=r.slice(0,-2),o=i.slice(0,-2),l=`.${i}`,a=`${s}.**`,u=Mn(e),c=u.filter(e=>e.startsWith(a)).map(e=>e.slice(a.length)),h=e=>v(`[wcs/recursion-declaration-invalid] ${e}`);for(let e of c){(e===`.${o}`||e.startsWith(`.${o}.`))&&h(`"${a}${e}" names the recursion structure itself (the "${o}" lists): recursive getters compute values over the nodes.`);for(let t of c)t.length>e.length&&t.endsWith(e)&&new RegExp(`^(?:${Hn(l)})+$`).test(t.slice(0,t.length-e.length))&&h(`"${a}${e}" and "${a}${t}" expand to the same concrete path at different depths (they differ by whole repetitions of "${i}"). Rename one of them.`);let t=new RegExp(`^${Hn(r)}(?:${Hn(l)})*${Hn(e)}$`);for(let n of u)!n.includes("**")&&t.test(n)&&h(`"${n}" is already defined on the state, so the recursive getter "${a}${e}" cannot expand to it.`)}}(n),function(e){Tn.delete(e),xn.has(e)&&jn(e)}(t)},c.tt=d(p,c.tt,(e,t)=>Object.hasOwn(qn,t)?_(1701,[t,qn[t]]):void 0)}},Kn={},Gn=/\.\d/,Vn=new Set(Object.getOwnPropertyNames(Object.prototype)),Jn=0,Qn=!1,Xn=null,Yn=()=>{Qn=!1,Jn++};function Zn(){if(null===Xn)if("function"==typeof MessageChannel){let e=new MessageChannel;e.port1.onmessage=Yn,e.port1.unref?.(),Xn=()=>e.port2.postMessage(0)}else Xn=()=>setTimeout(Yn,0);return Qn||(Qn=!0,Xn()),Jn}function er(e,t){let n=new Set,r=[e];for(;r.length>0;){let e=r.pop();if(!n.has(e)){n.add(e);for(let n of e.$e){for(let r of t)if(n.Q(r)&&(n.n===r.n||!(r.n<e.n&&e.f[r.n+1].Q(r))))return!0;null!==n.getter&&r.push(n)}}}return!1}var tr=class{constructor(e,t){this.active=!1,this.Ye=new Map,this.n=0,this.$o=-1,this.Cn=new Set,this._e=null,this.engine=e,this.st=t}Zo(){let e=this.engine;this.Ye.clear();for(let t of this.st)t.getter=null!==t.p.getter||t.p.de,t.s=new WeakMap,this.prime(t,()=>{0===t.p.n?t.getter&&t.s.set(Kn,e.v(t.p,null)):this.In(t.p,1,null,n=>{t.getter&&this.prime(t,()=>t.s.set(n,e.v(t.p,n)))})});this.active=!0}prime(e,t){try{t()}catch(t){console.error(`[@wcstack/state] $watch initial evaluation of "${e.t}" threw.`,t),c.ot?.(this.engine,{type:"state:watch-error",phase:"prime",path:e.t,error:t})}}No(){this.active=!1,this.Ye.clear()}In(e,t,n,r){let i=this.engine.De(n,e.f[t]);for(let n of i.u)t===e.n?r(n):this.In(e,t+1,n,r)}an(e,t,n,r){let i=this.Ye.get(e);void 0===i&&this.Ye.set(e,i=new Map);let s=i.get(t);void 0===s?i.set(t,[n,this.n,r]):(s[1]<this.n&&(s[1]=this.n),s[2]||=r)}he(e,t,n,r,i){if(this.active){(this._e??=new Set).add(e);for(let s of this.st){let o=s.p;o.n!==e.n||!o.Q(e)||this.an(s,t,s.getter?s.s.get(t??Kn):o===e&&i&&this.engine.Dt&&(null===r||"object"!=typeof r&&"function"!=typeof r)?n:void 0,!0)}}}ye(e,t){if(this.active)for(let n of this.st)(n.getter||=null!==n.p.getter||n.p.de)&&n.p.n===e.n&&n.p.Q(e)&&this.an(n,t,n.s.get(t??Kn),!1)}Yt(e,t){if(!this.active)return;let n=null;for(let r of this.st){let i=r.p;if(!(i.n<e.n||i.f[e.n]!==e.o)){n??=new Set(t);for(let t of e.u)n.has(t)||(i.n===e.n?this.an(r,t,void 0,!0):this.In(i,e.n+1,t,e=>this.an(r,e,void 0,!0)))}}}Te(){let e=this._e;if(this._e=null,!this.active||0===this.Ye.size)return;let t=this.Ye;this.Ye=new Map;let n=this.engine,r=[];for(let i of this.st){let s=t.get(i);if(void 0===s)continue;let o,l=[...s].filter(([e])=>null===e||e.y);l.length>1&&l.sort((e,t)=>rr(e[0],t[0]));for(let[t,[s,a,u]]of l){let l,h="evaluate",d=n.c;this.n=a+1,n.xe++;try{if(l=n.v(i.p,t),i.getter&&(i.s.set(t??Kn,l),Object.is(l,s)&&(Gn.test(i.t)||null!==t&&!u&&!(o??=null!==e&&er(nr(i.p),e)))))continue;if(a>32){r.includes(i.t)||r.push(i.t);continue}n.c=t,c.ot?.(n,{type:"state:watch-fired",path:i.t}),h="handler",i.handler.call(n.proxy,l,s,...n.W(t))}catch(e){console.error(`[@wcstack/state] $watch "${i.t}" failed; the other watches still run.`,e),c.ot?.(n,{type:"state:watch-error",phase:h,path:i.t,error:e})}finally{n.c=d,this.n=0,n.xe--}}}r.length>0&&this.xo(r)}xo(e){let t=Zn();t!==this.$o&&(this.$o=t,this.Cn.clear());let n=e.filter(e=>!this.Cn.has(e));if(0!==n.length){for(let e of n)this.Cn.add(e);console.error("[@wcstack/state] $watch handlers / $stream restarts kept writing for 32 batches; the chain is cut (nothing is rolled back)."),c.ot?.(this.engine,{type:"state:watch-chain-limit",maxDepth:32,paths:n})}}};function nr(e){for(;null===e.getter&&null!==e.d;)e=e.d;return e}function rr(e,t){let n=[],r=[];for(let t=e;null!==t;t=t.l.re)n.unshift(t.b);for(let e=t;null!==e;e=e.l.re)r.unshift(e.b);for(let e=0;e<n.length&&e<r.length;e++)if(n[e]!==r[e])return n[e]-r[e];return n.length-r.length}var ir="$streamStatus",sr="$streamError",or=new Set(Object.getOwnPropertyNames(Object.prototype)),lr=!1;function ar(e,t){for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return void 0!==e.get||void 0!==e.set||"function"==typeof e.value}return!1}var ur=class{constructor(e,t,n){this.engine=e,this.entries=t,this.D=n}set(e,t,n){lr=!0;try{this.engine.P(this.engine.o(`${e}.${t}`),null,n)}finally{lr=!1}}er(){for(let e of this.entries)this.start(e,!0)}tr(){for(let e of this.entries)e.at=!1,e.Y?.abort(),e.Y=null}nr(){for(let e of this.entries)e.at=!1,null!==e.Y&&(e.Y.abort(),e.Y=null),this.set(ir,e.name,"idle")}ye(e){let t=this.D.n;for(let n of this.entries)n.g===e&&(n.n=n.at?Math.max(n.n,t):t,n.at=!0)}Te(){let e=this.engine,t=this.D,n=[];for(let i of this.entries){if(!i.at)continue;let s=i.n;if(i.at=!1,s>32)n.push(i.name),i.g.J=r;else{t.n=s+1,e.xe++;try{this.start(i,!1)}finally{e.xe--,t.n=0}}}n.length>0&&t.xo(n)}start(e,t){let n,i=this.engine;if(null!==e.Y&&e.Y.abort(),e.Y=null,null!==e.g){let s=e.g;s.getter=e.args;let o=s.$e.slice();cr(s);try{n=i.read(s,null),function(e,t,n){null!==n&&"function"==typeof n?.then&&v(`$stream "${e}": args must be synchronous (it returned a Promise).`);for(let n of t.$e)n.n>0&&v(`$stream "${e}": args must not read a wildcard path ("${n.t}").`),(n.t===e||n.t===`${ir}.${e}`||n.t===`${sr}.${e}`)&&v(`$stream "${e}": args must not read the stream itself ("${n.t}").`)}(e.name,s,n)}catch(n){cr(s);for(let e of o)e.jn(s);if(s.J=r,t)throw n;return this.set(sr,e.name,n),void this.set(ir,e.name,"error")}}let s=new AbortController;e.Y=s,i.P(i.o(e.name),null,e.V),this.set(sr,e.name,null),this.set(ir,e.name,"active"),this.or(e,s,n)}async or(e,t,n){let r=this.engine,i=t.signal,s=()=>!i.aborted&&e.Y===t,o=r.o(e.name),l=this.D.n,a=Zn(),u=e=>{Zn()===a&&(this.D.n=l);try{e()}finally{this.D.n=0}},c=e.V;try{let t=await e.source(n,i);if(!s())return;let l=t=>{c=void 0!==e.Ro?e.Ro(c,t):t,u(()=>r.P(o,null,c))};if(null!==t&&"function"==typeof t?.getReader){let e=t.getReader();for(i.addEventListener("abort",()=>{e.cancel().catch(()=>{})});;){let t=await e.read();if(!s())return;if(t.done)break;l(t.value)}}else{if(null===t||"function"!=typeof t?.[Symbol.asyncIterator])throw new TypeError(`$stream "${e.name}": source must return an async iterable or a ReadableStream`);{let e=t[Symbol.asyncIterator]();for(i.addEventListener("abort",()=>{e.return?.()});;){let t=await e.next();if(!s())return;if(t.done)break;l(t.value)}}}if(!s())return;e.Y=null,u(()=>this.set(ir,e.name,"done"))}catch(n){if(!s())return;e.Y=null,t.abort(),u(()=>{this.set(sr,e.name,n),this.set(ir,e.name,"error")})}}};function cr(e){for(let t of e.$e){let n=t.G.indexOf(e);n>=0&&t.G.splice(n,1),t.Ft.delete(e)}e.$e.length=0,e.J=t}var hr=new WeakMap;function dr(e){let t=hr.get(e);return t?.target===e.target?t:void 0}function fr(e,t){let n=new tr(e,function(e,t){if(void 0===t)return[];(null===t||"object"!=typeof t)&&v("$watch must be an object mapping paths to handler functions.");let n=[];for(let r of Object.keys(t)){let i=t[r];(""===r||"$"===r[0]||r.includes("@")||Vn.has(r))&&v(`$watch path "${r}" is not a path of the state tree.`),"function"!=typeof i&&v(`$watch entry "${r}" must be a function.`);let s=e.o(r);c.go?.(e,s,!0),n.push({t:r,p:s,handler:i,getter:!1,s:new WeakMap})}return n}(e,t.$watch)),r=new ur(e,function(e,t){let n=t.$stream;if(void 0===n)return[];(null===n||"object"!=typeof n)&&v("$stream must be an object mapping stream names to definitions.");let r=[],i={},s={};for(let o of Object.keys(n)){let l=n[o];(""===o||"$"===o[0]||/[.*]/.test(o)||or.has(o))&&v(`$stream entry "${o}" must be a flat property name.`),(null===l||"object"!=typeof l)&&v(`$stream entry "${o}" must be an object.`);let a=l.source,u=l.fold,c=l.args,h=l.initial;"function"!=typeof a&&v(`$stream entry "${o}" needs a source function.`),void 0!==u&&"function"!=typeof u&&v(`$stream entry "${o}": fold must be a function.`),void 0!==u&&!("initial"in l)&&v(`$stream entry "${o}": fold needs an initial value.`),void 0!==c&&"function"!=typeof c&&v(`$stream entry "${o}": args must be a function.`),ar(t,o)&&v(`$stream entry "${o}" collides with a getter, setter or method of the state.`),void 0===t[o]&&(t[o]=h),i[o]="idle",s[o]=null,r.push({name:o,source:a,Ro:u,V:h,Y:null,at:!1,n:0,g:void 0===c?null:e.o(`$streamArgs.${o}`),args:void 0===c?null:function(){return c(this)}})}return t[ir]=i,t[sr]=s,r}(e,t),n),i=hr.get(e);void 0!==i&&(i.D.No(),i.Pt.tr()),hr.set(e,{D:n,Pt:r,Xe:i?.Xe??!1,target:t})}function pr(e,t){let n=hr.get(e);if(void 0!==n&&"mounting"!==t&&!document.documentElement?.hasAttribute("data-wcs-server")&&("reset"!==t&&(n.Xe="connected"===t),n.target===e.target)){if("disconnected"===t)return n.D.No(),void n.Pt.nr();n.Xe&&(n.D.Zo(),n.Pt.er())}}var mr=["$streamStatus","$streamError"],gr={name:"temporal",install(){c.se=h(c.se,fr),c.element=h(c.element,pr),c.he=h(c.he,(e,t,n,r,i,s)=>dr(e)?.D.he(t,n,r,i,s)),c.ye=h(c.ye,(e,t,n)=>{let r=dr(e);void 0!==r&&(r.D.ye(t,n),r.Pt.ye(t))}),c.Yt=h(c.Yt,(e,t,n)=>dr(e)?.D.Yt(t,n)),c.Te=h(c.Te,e=>{let t=dr(e);void 0!==t&&(t.D.Te(),t.Pt.Te())}),c.tt=d(p,c.tt,(e,t)=>{let n=t.split(".",1)[0];if(mr.includes(n))return n===t?e.target[t]:e.read(e.o(t),null)}),c.Pe=d(f,c.Pe,(e,t)=>(!lr&&36===t.t.charCodeAt(0)&&mr.includes(t.t.split(".",1)[0])&&v(`"${t.t}" is read-only (the stream runtime owns it).`),!1))}},yr=new WeakMap,br=!1,vr=/^(?!prototype$)[^\d.*$][^.*]*$/;function wr(e,t){let n=t.$listKeys,r=new Map;if(void 0!==n){(null===n||"object"!=typeof n)&&v("$listKeys must be an object mapping list paths to a key field or function.");for(let t of Object.keys(n)){let i=n[t];"string"==typeof i?r.set(e.o(t),e=>e[i]):"function"==typeof i?r.set(e.o(t),i):v(`$listKeys "${t}" must be a field name or a function.`)}}yr.set(t,r)}function _r(e){if(null===e||"object"!=typeof e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function $r(e,t,n){let r=new Map;for(let i of t){_r(i)||v(`$listKeys "${e}": rows must be plain objects.`);let t=n(i);null==t&&v(`$listKeys "${e}": a row has no key.`),r.has(t)&&v(`$listKeys "${e}": duplicate key ${JSON.stringify(t)}.`),r.set(t,i)}return r}function kr(e,t,n,r){if(br||!Array.isArray(r))return!1;let i=yr.get(e.target)?.get(t);if(void 0===i)return!1;let s=e.wt(t,n);if(!Array.isArray(s)||s===r)return!1;let o=$r(t.t,s,i);$r(t.t,r,i);let l=[],a=[],u=s.length===r.length;for(let e=0;e<r.length;e++){let t=r[e],n=o.get(i(t));l.push(n??t),void 0!==n&&a.push([e,n,t]),l[e]!==s[e]&&(u=!1)}let c=[];for(let[e,t,n]of a){for(let r of Object.keys(n))Object.is(t[r],n[r])||c.push([e,r,n[r]]);for(let r of Object.keys(t))!(r in n)&&null!==t[r]&&c.push([e,r,null])}if(u&&0===c.length)return!0;if(!u){br=!0;try{e.P(t,n,l)}finally{br=!1}}if(c.length>0){let r=e.De(0===t.n?null:n,t);for(let[n,i,s]of c){if("__proto__"===i)continue;let o=r.u[n],l=vr.test(i)?e.o(`${t.t}.*.${i}`):null;null===l?.getter?e.P(l,o,s):(o.T[i]=s,e.P(e.o(`${t.t}.*`),o,o.T,!0))}}return!0}var Sr={name:"list-keys",install(){c.se=h(c.se,wr),c.Pe=d(f,c.Pe,kr)}},Nr=new WeakMap,Er=new WeakMap,Ar="will not graft: the root state failed to initialize.",Cr=new WeakSet,xr=new WeakMap,Tr=["$stream","$streams","$scan","$recursion","$watch","$listKeys","$renderedCallback","$updatedCallback","$behavior","$features"],Pr=["$commandTokens","$eventTokens","$on","$errorCallback"],Or=e=>`[@wcstack/state] <${ee.tagNames.state} mount="${e}">`,Lr=new Set(["$getAll","$setAll","$resolve","$postUpdate","$dependOn","$eq","$eqIndex"]),Mr=e=>e?.element?.isConnected?e:void 0;function Ir(e){let t=Er.get(e);return void 0!==t&&!Array.isArray(t)&&t.isConnected}function jr(e,t){let n=Er.get(t);if(Er.delete(t),Array.isArray(n))for(let t of n)zr(t,e)}function Rr(e){let t=Nr.get(e.root);t?.get(e.t)===e&&t.delete(e.t)}function Hr(e,t){console.error(`${Or(e.t)} ${t}`),Rr(e),e.Ge?.(),e.Ge=null}function Wr(e,t){let n=e.state?.[t];if("function"==typeof n)try{let t=n.call(e.chroot);null!==t&&"object"==typeof t&&"function"==typeof t.then&&t.then(void 0,e=>console.error(e))}catch(e){console.error(e)}}function zr(e,t){if(Cr.has(t))return Hr(e,"will not graft: its component is wired to its host.");let n=e.state,r=t.target,i=e.t.split("."),s=r;for(let e of i)s=s?.[e];if(void 0!==s&&!0!==t.hydrated)return Hr(e,`will not graft: the root state already has "${e.t}".`);let o=function(e,t){let n=e=>`${t}.${e}`;return new Proxy({},{get(t,r){if("symbol"==typeof r)return;if(36!==r.charCodeAt(0))return e.proxy[n(r)];let i=e.proxy[r];return"$eqPath"===r?(e,t)=>i(n(e),n(t)):Lr.has(r)&&"function"==typeof i?(e,...t)=>i(n(e),...t):i},set:(t,r,i)=>"symbol"!=typeof r&&(e.proxy[n(r)]=i,!0)})}(t,e.t);e.chroot=o;let l={},a={},u=new Set;for(let t=n;null!==t&&t!==Object.prototype;t=Object.getPrototypeOf(t))for(let n of Object.getOwnPropertyNames(t)){if(u.has(n)||"constructor"===n)continue;u.add(n);let{get:r,set:i,value:s}=Object.getOwnPropertyDescriptor(t,n);if(void 0!==r||void 0!==i)a[`${e.t}.${n}`]={get:r&&function(){return r.call(o)},set:i&&function(e){i.call(o,e)}};else{if("$"===n[0])continue;if("function"==typeof s){let t=s.bind(o);a[`${e.t}.${n}`]={get:()=>t}}else l[n]=s}}if(void 0===s){for(let e=1;e<i.length;e++){let n=t.o(i.slice(0,e).join("."));null==t.wt(n,null)&&t.P(n,null,{})}t.P(t.o(e.t),null,l)}t.Yn(Object.defineProperties({},a));for(let e in a)t._e(t.o(e),null);e.engine=t;let c=xr.get(t);void 0===c&&xr.set(t,c=[]),c.push(e),e.el.isConnected&&Wr(e,"$connectedCallback"),e.Ge?.(),e.Ge=null}function Dr(e,t){let n=Er.get(e);if(Array.isArray(n))for(let e of n)Hr(e,Ar);Er.set(e,t)}var Ur=new WeakMap;function Fr(e,t){let n=e.getAttribute("mount");if(null===n)return null;let r={el:e,root:t,t:n,state:null,engine:null,chroot:null,Ge:null},i=null;if(function(e){return""!==e&&e.split(".").every(e=>""!==e&&!/[*$#@\s]/.test(e))}(n))if(e.hasAttribute(ee.bindAttributeName))i='injections (data-wcs="state.<key>: …") are not supported — read the root path in a root getter.';else{let e=Nr.get(t);void 0===e&&Nr.set(t,e=new Map);let s=e.get(n);if(void 0!==s&&s!==r&&(null===s.engine?s.el.isConnected:Mr(s.engine)))i=`will not graft: another volume already holds "${n}".`;else{if(null===s?.engine){let e=Er.get(t);Array.isArray(e)&&Er.set(t,e.filter(e=>e!==s)),s.Ge?.(),s.Ge=null}e.set(n,r)}}else i='has an invalid mount path: it must be a static path (no "*", "$", "#", "@").';return{vo:!0,start(e){if(null!==i)return Hr(r,i);if(Nr.get(t).get(n)===r){for(let t of Tr)if(void 0!==e[t])return Hr(r,`${t} is not run in a volume — declare it on the root state.`);for(let t of Pr)void 0!==e[t]&&console.warn(`${Or(n)} ${t} is not run in a volume (it belongs to the root).`);return r.state=e,new Promise(e=>{r.Ge=e;let n=Mr(Ot.get(t)),i=Er.get(t);void 0!==n?zr(r,n):Ir(t)?Hr(r,Ar):Er.set(t,[...Array.isArray(i)?i:[],r])})}},Xe(){null!==r.engine&&Wr(r,"$connectedCallback")},On(){null!==r.engine&&Wr(r,"$disconnectedCallback")},reset(){v(`re-setting a volume is not supported: its data was copied into the root tree at "${n}" — write the paths under it on the root instead.`)}}}var qr=new WeakMap,Br=new WeakMap;function Kr(e,t){let n=e[t];if(void 0===n)return[];Array.isArray(n)||v(`${t} must be an array of state member names.`);let r=new Set;for(let e of n)("string"!=typeof e||""===e)&&v(`${t} entries must be non-empty strings.`),"$"===e[0]&&v(`${t} entry "${e}": internal ($) members are never exposed.`),r.has(e)&&v(`${t} entry "${e}" is duplicated.`),r.add(e);return n}function Gr(e,t){let n=t.host;if(void 0===n||!n.hasAttribute("data-wc-definition"))return null;let r=document.createDocumentFragment();for(let e of[...t.childNodes])r.appendChild(e.cloneNode(!0));let i=t.mode;return{start(t){e.hasAttribute("bind-component")&&v("DCC: a <wcs-state bind-component> cannot define a component (use one mechanism)."),function(e,t,n,r){e.includes("-")||v(`DCC: <${e} data-wc-definition> is not a valid custom element name.`),void 0!==customElements.get(e)&&v(`DCC: <${e}> is already defined.`);let i=function(e){let t=new Map;for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n))for(let e of Object.getOwnPropertyNames(n))"constructor"===e||"$"===e[0]||t.has(e)||t.set(e,Object.getOwnPropertyDescriptor(n,e));let n=e.$stream;if(null!==n&&"object"==typeof n)for(let e of Object.keys(n))t.has(e)||t.set(e,{value:void 0});return t}(r),s=Kr(r,"$bindables"),o=Kr(r,"$commands");for(let e of s){let t=i.get(e);void 0===t&&v(`$bindables entry "${e}" does not exist on the state.`),"function"==typeof t.value&&v(`$bindables entry "${e}" is a method: list it in $commands.`)}for(let e of o){let t=i.get(e);void 0===t&&v(`$commands entry "${e}" does not exist on the state.`),"function"!=typeof t.value&&v(`$commands entry "${e}" is not a method: list it in $bindables.`)}let l={tag:e,bindables:s},a=new WeakMap,u=new WeakMap,c=r=>{if(a.has(r))return a.get(r);if(r.hasAttribute("data-wc-definition"))return null;let i=r.attachShadow({mode:n});i.appendChild(t.cloneNode(!0));let o=i.querySelector(ee.tagNames.state);return a.set(r,o),qr.set(r,l),null===o&&s.length>0&&console.warn(`[@wcstack/state] DCC: <${e}> declares $bindables but its content has no <${ee.tagNames.state}>: no change events.`),o},h=e=>c(e)?.engine??null,d=e=>Promise.resolve(c(e)?.initializePromise).then(()=>{let t=u.get(e);u.delete(e);let n=h(e);if(void 0!==t&&null!==n)for(let[e,r]of t)n.proxy[e]=r});class f extends HTMLElement{static{this.wcBindable=0===s.length&&0===o.length?null:{protocol:"wc-bindable",version:1,properties:s.map(t=>({name:t,event:`${e}:${t}-changed`,getter:e=>e.target[t]})),inputs:s.map(e=>({name:e})),...0===o.length?{}:{commands:o.map(e=>({name:e,async:!0}))}}}connectedCallback(){null!==c(this)&&d(this)}get stateElement(){return c(this)}}for(let[e,t]of i)"function"==typeof t.value?Object.defineProperty(f.prototype,e,{configurable:!0,value(...t){return d(this).then(()=>{let n=h(this);return null===n?void 0:n.proxy[e].apply(n.proxy,t)})}}):Object.defineProperty(f.prototype,e,{configurable:!0,get(){return h(this)?.proxy[e]},set(t){let n=h(this);if(null!==n)n.proxy[e]=t;else{let n=u.get(this);void 0===n&&u.set(this,n=[]),n.push([e,t])}}});customElements.define(e,f)}(n.localName,r,i,t)},Xe(){},On(){},reset(){v("re-setting a DCC definition is not supported: each instance loads its own state.")}}}var Vr=new WeakMap,Jr=new WeakSet,Qr=new WeakMap,Xr=new WeakMap,Yr="data-wcs-wired",Zr=new WeakMap,ei=new WeakMap,ti=new WeakMap,ni=0,ri=new Set,ii={},si=["$watch","$stream","$renderedCallback"],oi=e=>e.split(".",1)[0];function li(e,t){let n=0;return e.split(".").map(e=>"*"===e?String(t[n++]):e).join(".")}function ai(e,t){let n=e.a,r=oi(e.name);if(!0!==document.documentElement?.hasAttribute("data-wcs-server"))n.removeAttribute(Yr);else if(!ci(n,r)){let e=n.getAttribute(Yr)?.split(" ")??[];e.includes(r)||n.setAttribute(Yr,[...e,r].join(" "))}Zr.get(n)?.ce===r&&v(`<${n.localName}>.${r} has loaded its state: the wiring "${e.name}" added afterwards cannot reach it — bind the host's wiring before the component loads.`);let i=Vr.get(n);void 0===i&&Vr.set(n,i=[]),i.push(e),t&&Jr.add(e);let s=Qr.get(n);return void 0===s&&Qr.set(n,s=new Map),s.has(r)||s.set(r,n[r]),Xr.get(n)?.(),!1}function ui(e){return e.localName.includes("-")&&null!==e.querySelector(`:scope > ${ee.tagNames.state}[bind-component]`)}function ci(e,t){let n=e.getAttribute(ee.bindAttributeName);return null!==n&&new RegExp(`(^|;)\\s*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[.#:]`).test(n)}function hi(e){let t=e.parentElement;for(;null!==t&&!ui(t);)t=t.parentElement;let n=Ot.get(t??e.getRootNode()),r=n?.element;(r?.isConnected?r._:null===t)&&(null===t?zt(e):Mt(n,e))}var di=new Set;function fi(e,t){di.has(e)||(di.add(e),console.warn(`[@wcstack/state] ${t}`))}var pi=(e,t)=>t in e.state;function mi(e,t){let n=gi(e.state,t);return void 0!==n&&(void 0!==n.get||void 0!==n.set||"function"==typeof n.value)}function gi(e,t){for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e}}function yi(e,t,n){if(null!==n.getter)return;let r,i=e.host,s=i.engine,o=oi(n.t),l=i.entries.find(e=>e.E===n.t);if(void 0===l&&null!==n.d)return function(e,t){let n,r=t.d;for(;null!==r&&void 0===(n=e.ct.get(r));)r=r.d;if(null===r||void 0===n)return;let i=e.x,s=e.host.engine,o=s.o(n.p.t+t.t.slice(r.t.length));if(null===o.getter)return;let l=n,a=()=>{let n=bi(e,l.r);return 0===t.n?n:(s.resolve(li(o.t,[...s.W(n),...i.W(X(i.c,t.n))]),null),s.rr)};t.getter=()=>{let e=a();return o.n>0&&null===e?void 0:s.v(o,e)},null!==o.oe&&(t.oe=n=>{let r=a();vi(e,l.e,()=>s.P(o,r,n)),e.cn=t}),t.n>0&&(t.F=i.Oe++),e.ct.set(t,{e:l.e,p:o,r:l.r})}(e,n);if(0!==n.n)return;if(void 0!==l){if(l.E!==o?pi(i,o):mi(i,o))return;r=l.ue}else{if(null===t||null!==n.d||"$"===o[0]||pi(i,o))return;l=t,r=s.o(`${t.ue.t}.${o}`)}let a=l.r,u=l;n.getter=()=>s.v(r,bi(e,a)),n.oe=t=>{vi(e,u,()=>s.P(r,a,t)),e.cn=n},e.ct.set(n,{e:l,p:r,r:a})}function bi(e,t){return null!==t&&!t.y&&v(`The host row of <${e.host.el.localName}> was removed.`),t}function vi(e,t,n){let r=ri.has(e.x);ri.add(e.x),e.from=t;try{n()}finally{r||ri.delete(e.x),e.from=null}}var wi=(e,t)=>t||!ri.has(e.m.x)||null!==e.m.from&&e.m.from!==e.e;function _i(e,t){if(e.un===t||null===e.host.engine)return;e.un=t,ni+=t?1:-1;let n=e.host.engine,r=ti.get(n);void 0===r&&ti.set(n,r=new Map);for(let n of e.ae){let e=r.get(n.e.ue);void 0===e&&r.set(n.e.ue,e=new Map);let i=e.get(n.e.r);void 0===i&&e.set(n.e.r,i=new Set),t?i.add(n):(i.delete(n),0===i.size&&e.delete(n.e.r))}let i=e.host.entries.find(e=>""===e.E);if(void 0!==i){null===e.te&&function(e,t){let n=e.host,r=n.engine;e.te=new Map;let i=new Set;for(let s=n.state;null!==s&&s!==Object.prototype;s=Object.getPrototypeOf(s))for(let o of Object.getOwnPropertyNames(s)){if(i.has(o))continue;i.add(o);let l=Object.getOwnPropertyDescriptor(s,o);if(void 0===l.get&&void 0===l.set||"$"===o[0]||o.includes("*"))continue;let a=oi(o);if(o!==a&&!pi(n,a))continue;let u=r.o(`${t.ue.t}.${o}`);if(null===u.getter)Si(r,u,t.ue);else if(!$i.has(u.getter))continue;e.te.set(u,e.x.o(o))}}(e,i);for(let r of e.te.keys())t&&null===r.getter&&Si(n,r,i.ue),n.R.me(n,r,i.r);e.te.size>0&&n.Re(),t&&function(e,t){let n=e.host.engine;for(let[r,i]of e.te){let s=n.v(r.d,t.r);if(null===s||"object"!=typeof s||!(r.s in s))continue;let o=e.host.el.localName;fi(`${o}|${r.t}`,`[wcs/mount-export-shadowed] <${o}>.${e.host.ce}.${i.t} is exported at "${r.t}" 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,i)}}var $i=new WeakSet;function ki(e,t,n,r){let i=ti.get(e)?.get(t)?.get(n);if(void 0===i)return null;let s=null;for(let e of i)""!==e.e.E||!0!==e.m.te?.has(r)||e.m===s||(null!==s&&v(`[wcs/mount-export-ambiguous] "${r.t}" is exported by two mounted components on the same instance: <${s.host.el.localName}> and <${e.m.host.el.localName}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),s=e.m);return s}function Si(e,t,n){let r=t.d,i=t.s,s=()=>{let t=e.read(r,e.c);return null!==t&&"object"==typeof t&&i in t?t:null};t.getter=()=>{let r=s();if(null!==r)return r[i];let o=ki(e,n,e.c,t);return null===o?void 0:o.x.read(o.te.get(t),null)},$i.add(t.getter),t.oe=o=>{let l=null===s()?ki(e,n,e.c,t):null;if(null===l){let t=e.read(r,e.c);return void(null!==t&&"object"==typeof t&&(t[i]=o))}let a=l.te.get(t);void 0===gi(l.host.state,a.t)?.set&&v(`Cannot write to "${a.t}" on mounted <${l.host.el.localName}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),l.x.P(a,null,o)},t.n>0&&(t.F=e.Oe++)}function Ni(e,t,n,r,i,s){if(null!==t.getter)return e.R.me(e,t,n),void e.Re();if("*"===t.s){if(null===n)return;if(n.T=n.l.C[n.b],e.R.Kt(n),null!==n.h)for(let t of n.h.values())e.z(t)}else e.wn(t,n);c.he?.(e,t,n,r,i,s),e._e(t,n)}function Ei(e){let t=e.m.x;for(let[n,r]of e.m.ct)r.e===e.e&&(0===n.n?t.R.me(t,n,null):t.Zt(n.f[n.n],e=>t.R.me(t,n,e)));t.Re()}function Ai(e,t,n,r,i,s,o){let l=n.t.slice(t.t.length);if(""===l)return Ei(e);let a,u=e.m,c=u.x;if(""===e.e.E){a=l.slice(1);let e=oi(a);if("$"===e[0]||pi(u.host,e)||u.host.entries.some(e=>""!==e.E&&(a===e.E||a.startsWith(`${e.E}.`))))return}else a=e.e.E+l;let h=[];for(let e=t.n+1;e<=n.n;e++)h.push(X(r,e).b);c.resolve(li(a,h),null);let d=c.rp,f=c.rr;d.n>0&&null===f||Ni(c,d,f,i,s,o)}function Ci(e,t,n,r,i,s,o){if(0===ni)return;let l=ri.has(e);ri.add(e);try{let l=ei.get(e);!o&&void 0!==l&&l.un&&!ri.has(l.host.engine)&&function(e,t,n,r,i,s){let o,l=t;for(;null!==l&&void 0===(o=e.ct.get(l));)l=l.d;if(null===l||void 0===o)return;let a=e.host.engine;if(l===t&&e.cn===t)return void(e.cn=null);if(null!==o.r&&!o.r.y)return;let u=[...a.W(o.r),...e.x.W(n)];a.resolve(li(o.p.t+t.t.slice(l.t.length),u),null);let c=a.rp,h=a.rr;c.n>0&&null===h||vi(e,o.e,()=>Ni(a,c,h,r,i,s))}(l,t,n,r,i,s),o&&void 0!==l&&l.un&&null!==l.te&&function(e,t){let n=e.host.entries.find(e=>""===e.E),r=e.host.engine;for(let[i,s]of e.te)s===t&&(r.R.me(r,i,n.r),r.Re())}(l,t);let a=ti.get(e);if(void 0===a)return;for(let[e,l]of a)if(t.Q(e)){let a=l.get(0===e.n?null:X(n,e.n));if(void 0!==a)for(let l of[...a])wi(l,o)&&Ai(l,e,t,n,r,i,s)}else if(e.Q(t))for(let[e,r]of[...l])if(0===t.n||X(e,t.n)===n)for(let e of[...r])wi(e,o)&&Ei(e)}finally{l||ri.delete(e)}}async function xi(e,t,n,r,i){if(r===ii)return;let s=y(r);s&&await s;let o=Zr.get(t);o.engine&&r.$recursion&&v(`[wcs/mount-dollar-declaration] <${t.localName}>: $recursion is not run in a mounted component — declare it on the root state.`);let l=o.O;if(null!==l&&l.el!==e&&l.el.isConnected&&v(`<${t.localName}> already has a connected <${ee.tagNames.state} bind-component="${o.ce}">.`),null!==l&&_i(l,!1),null!==l&&function(e,t,n){let r=e.x,i=`[${ee.bindAttributeName}]`,s=e=>1===e.nodeType&&(e.matches(i)||null!==e.querySelector(i)),o=new Set,l=e=>{for(;null!==e&&e.parentNode!==n;)e=e.parentNode;null!==e&&o.add(e)},a=(e,t)=>{for(let n=e.Pn(t);null!==n&&n!==t;n=n.nextSibling)l(n);l(t)};for(let e of r.ie.values())for(let t of e)if(null===t.M)l(t.a);else for(let e of t.M.X)a(t.M,e.S);for(let e of r.ee.values())for(let t of[e.$,...e.L??[]])null!==t&&a(t,t.S);for(let t of e.j)t.parentNode===n&&s(t)&&o.add(t);if(0===o.size)return!1;let u=[...n.childNodes].filter(n=>n!==t&&!o.has(n)&&!e.j.includes(n)&&(s(n)||r.Bt&&n.textContent.includes("{{")));return u.length>0&&console.warn(`[@wcstack/state] <${e.host.el.localName}>: ${u.length} node(s) added beside the content taken over are not bound.`),!0}(l,e,n))return async function(e,t,n,r){e.el.engine=null,e.el=t,e.x.element=t,t.engine=e.x,e.j=e.j.filter(e=>e.parentNode===n),t.isConnected?await Ti(e,r):r()}(l,e,n,i);let a=new Z(r,new Ut);a.element=e,e.engine=a,function(e,t){let n=new Map;for(let e=t;null!==e&&e!==Object.prototype;e=Object.getPrototypeOf(e))for(let t of Object.getOwnPropertyNames(e)){let r=Object.getOwnPropertyDescriptor(e,t).value;"function"==typeof r&&"constructor"!==t&&n.set(r,null)}let r=(t,n,r)=>Reflect.apply(t,e.proxy,r);e._=e=>{let t=n.get(e);return null===t&&n.set(e,t=new Proxy(e,{apply:r})),t}}(a,r);let u={el:e,j:[],x:a,host:o,ae:[],ct:new Map,un:!1,cn:null,from:null,te:null};for(let e of o.entries)u.ae.push({m:u,e:e});o.O=u,ei.set(a,u);let h=null===o.engine;h?c.element?.(a,"mounting"):(function(e){let t=e.x,n=e.host,r=n.engine,i=n.el.localName,s=n.entries.find(e=>""===e.E)??null;for(let e of n.entries){if(""===e.E)continue;let t=oi(e.E);pi(n,t)&&(e.E!==t||mi(n,t))&&fi(`${i}.${e.E}`,`[wcs/mount-own-key-shadow] <${i}>: "${n.ce}.${e.E}" is hidden by the component's own "${t}"; rename one side.`)}if(null!==s){let e=r.v(s.ue,s.r);if(null!==e&&"object"==typeof e)for(let t of Object.keys(n.state))"$"!==t[0]&&t in e&&!n.entries.some(e=>e.E===t)&&fi(`${i}.${t}`,`[wcs/mount-own-key-shadow] <${i}>: its own "${t}" hides "${s.ue.t}.${t}" — remove the default to read the tree, or rename it to keep it private.`)}let o=si.filter(e=>void 0!==n.state[e]);o.length>0&&fi(`${i}.${n.ce}$`,`[wcs/mount-dollar-declaration] <${i}>: ${o.join(", ")} ${1===o.length?"is":"are"} not run in a mounted component — declare it on the root state.`);let l=t.et;t.et=n=>{yi(e,s,n),l.call(t,n)};let a=[...t.B.all()];for(let t of a)yi(e,s,t);for(let e of a)l.call(t,e);let u=n.entries.filter(e=>null!==e.r);if(u.length>0){let e=t.qt;t.qt=()=>{u.every(e=>e.r.y)&&e.call(t)}}}(u),_i(u,!0),Cr.add(a),jr(a,n));let d=c.ir?.(n);Lt(a,n),d?.(),u.j=[...n.childNodes],Dt(),h&&a.bn(),Object.defineProperty(t,o.ce,{configurable:!0,enumerable:!0,get:()=>a.proxy});let f=t.$stateReadyCallback;if("function"==typeof f)try{let e=f.call(t,o.ce);null!==e&&"object"==typeof e&&"function"==typeof e.then&&e.then(void 0,e=>console.error(e))}catch(e){console.error(e)}i(),e.isConnected?(await a.we("$connectedCallback"),h&&e.isConnected&&c.element?.(a,"connected")):_i(u,!1)}async function Ti(e,t){_i(e,!0);for(let t of e.ae)Ei(t);t?.(),!e.broken&&(await e.x.we("$connectedCallback"),null===e.host.engine&&e.el.isConnected&&c.element?.(e.x,"connected"))}function Pi(e,t){let n=e.getAttribute("bind-component");if(null===n)return function(e,t){return e.connectedCallbackPromise.catch(()=>{let n=Ot.get(t)?.element;if(!(e._||void 0!==n&&n!==e&&n.isConnected)){Dr(t,e);for(let e of Ur.get(t)??[])e()}}),null}(e,t);let r=e.parentNode,i=r instanceof ShadowRoot,s=i?r.host:r instanceof Element?r:null,o=()=>{let t=null===s?void 0:Zr.get(s)?.O;return t?.el===e?t:null},l=t=>{throw i&&Dr(r,e),t},a=!1;return{Lt:()=>(null!==s&&s.localName.includes("-")?async function(e,t,n,r){let i=n.localName;(["state","src","json"].some(t=>e.hasAttribute(t))||null!==e.querySelector('script[type="module"]'))&&v(`<${ee.tagNames.state} bind-component> takes its state from <${i}>.${t}: it cannot also load one (state / src / json / an inline script).`),await Oe(n).whenDefined(i);let s=Zr.get(n);if(void 0!==s)return s.ce!==t&&v(`<${i}> already has a <${ee.tagNames.state} bind-component="${s.ce}">.`),s.state;let o=()=>(Vr.get(n)??[]).filter(e=>oi(e.name)===t),l=ci(n,t);if(l&&0===o().length&&hi(n),0===o().length&&(l||((e,t)=>!0===e.getAttribute(Yr)?.split(" ").includes(t))(n,t))){let e;await new Promise((r,s)=>{Xr.set(n,r),e=function(e,t){Ir(e)&&t();let n=Ur.get(e)??new Set;return Ur.set(e,n.add(t)),()=>n.delete(t)}(n.getRootNode(),()=>s(new Error(`[@wcstack/state] <${i}>.${t} will not mount: the root state failed to initialize.`)))}).finally(()=>e())}Xr.delete(n);let a=o(),u=Qr.get(n),c=void 0!==u&&u.has(t)?u.get(t):n[t];if((null===c||"object"!=typeof c)&&v(`"bind-component": <${i}>.${t} must be an object (the component's state), got ${null===c?"null":typeof c}.`),0===a.length&&r){let e=new Error(`[@wcstack/state] A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${i}>, or mount it from the host (${ee.bindAttributeName}="${t}: path").`);return queueMicrotask(()=>{throw e}),ii}let h=[];for(let e of a){let r=e.name===t?"":e.name.slice(t.length+1);h.some(e=>e.E===r)&&v(`<${i}> maps "${e.name}" twice.`);let s=r.split(".").indexOf("*");if(s>=0){let n=r.split(".").slice(0,s).join(".");v(`<${i}> maps "${e.name}": the component-side path of a mount cannot contain "*"${""===n?"":` — map the list itself ("${t}.${n}: <the host's list>")`}.`)}h.push({E:r,ue:e.o,r:e.r,ro:Jr.has(e)}),e.engine.kn(e),""!==r&&delete n[e.name]}let d=0===a.length?function(e){let t=Object.getOwnPropertyDescriptors(e),n=Object.isFrozen(e);for(let e of Object.values(t))"value"in e&&!1===e.writable&&(e.writable=!0,n=!0);return n?Object.create(Object.getPrototypeOf(e),t):e}(c):c;return Zr.set(n,s={el:n,ce:t,state:d,engine:0===a.length?null:a[0].engine,entries:h,O:null}),d}(e,n,s,!i):Promise.reject(new Error(`[@wcstack/state] "bind-component" requires <${ee.tagNames.state}> to be a direct child of a custom element.`))).catch(l),async start(t,n){await xi(e,s,i?r:s,t,()=>{a=!0,n()}).catch(e=>{let t=o();return!a&&null!==t&&(t.broken=!0),l(e)})},Xe(){let t=o();null!==t?Ti(t).catch(e=>console.error(e)):a?Promise.resolve().then(()=>{if(e.parentNode===r)return xi(e,s,i?r:s,Zr.get(s).state,()=>{})}).catch(e=>console.error(e)):Xr.has(s)&&hi(s)},On(){let e=o();null!==e&&(_i(e,!1),!e.broken&&(e.x.we("$disconnectedCallback"),null===e.host.engine&&c.element?.(e.x,"disconnected")))},reset(){v(`re-setting a component's state is not supported: write <${s?.localName}>.${n} instead.`)}}}var Oi={name:"scopes",install(){c.it=d(m,c.it,Fr),c.it=d(m,c.it,Gr),c.it=d(m,c.it,Pi),c.Jo=ai,c.yo=ui,c.element=h(c.element,(e,t)=>{if("mounting"!==t)return function(e,t){let n=xr.get(e)??[];if("disconnected"===t)for(let e of n)Rr(e);else if("reset"!==t&&Mr(Ot.get(e.root))===e){jr(e,e.root);for(let e of n)Nr.get(e.root).has(e.t)||Nr.get(e.root).set(e.t,e)}}(e,t);let n=e.element.getRootNode();jr(e,n),function(e,t){let n=t.host,r=void 0===n?void 0:qr.get(n);void 0!==r&&Br.set(e,{host:n,def:r})}(e,n)}),c.he=h(c.he,(e,t,n,r,i,s)=>{(function(e,t,n,r){let i=Br.get(e);if(void 0===i)return;let s=t.t.split(".",1)[0];if(!i.def.bindables.includes(s))return;let o=r&&t.t===s;i.host.dispatchEvent(new CustomEvent(`${i.def.tag}:${s}-changed`,{detail:o?n:void 0,bubbles:!0}))})(e,t,i,s),Ci(e,t,n,r,i,s,!1)}),c.ye=h(c.ye,(e,t,n)=>Ci(e,t,n,void 0,void 0,!1,!0)),c.Pe=d(f,c.Pe,(e,t,n,r,i)=>(function(e,t){let n=xr.get(e);if(void 0!==n&&0===t.n)for(let{t:e}of n)e.startsWith(`${t.t}.`)&&v(`writing "${t.t}" would replace the volume grafted at "${e}"; write the paths under it instead.`)}(e,t),function(e,t,n){let r,i=ei.get(e);if(void 0===i)return!1;for(let e=t;null!==e&&void 0===r;e=e.d)r=i.ct.get(e);if(void 0===r)return!1;let s=r.e;return!((null===s.r||s.r.y)&&!s.ro)&&(!!n||(bi(i,s.r),void v(`[wcs/mount-readonly] <${i.host.el.localName}> cannot write "${t.t}": it is mounted read-only ("${i.host.ce}${""===s.E?"":`.${s.E}`}#ro: ${s.ue.t}"). Write it on the host, or drop #ro from the mount.`)))}(e,t,i)));let e=c.se;c.se=(t,n)=>{let r=xr.get(t);void 0!==r&&r.length>0&&v(`re-setting a root state with grafted volumes (${r.map(e=>e.t).join(", ")}) is not supported: their data is part of the tree.`),function(e){let t=ti.get(e);if(void 0===t)return!1;for(let e of t.values())if(e.size>0)return!0;return!1}(t)&&v("re-setting a root state with mounted components is not supported: they read its data."),e?.(t,n)}}},Li="$recursion",Mi=new WeakMap,Ii=new WeakSet,ji=new WeakSet,Ri=0,Hi=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Wi=e=>`[wcs/recursion-${e}]`;function zi(e,t){let n=n=>v(`${Wi("declaration-invalid")} ${Li} ${e} "${String(t)}" ${n}`);("string"!=typeof t||""===t)&&v(`${Wi("declaration-invalid")} ${Li} ${e} must be a non-empty string.`);let r=t.split(".");(r.length<2||"*"!==r[r.length-1])&&n('must end with ".*" (a list element).');for(let e=0;e<r.length-1;e++){let t=r[e];""===t&&n("must not contain empty path segments."),("*"===t||"**"===t||/^\d/.test(t))&&n('must have exactly one "*", at the end.'),t.includes("#")&&n('must not contain "#".')}return"$"===t[0]&&n('must not start with "$".'),t}var Di=(e,t)=>`${e.l}.*${e.step.repeat(t)}`;function Ui(e,t){let n=`${e.l}.**`,r=t.slice(n.length);return(!t.startsWith(n)||""!==r&&"."!==r[0]||r.includes("**"))&&v(`[wcs/recursion-anchor] "${t}" does not start at the recursion anchor "${e.l}.*".`),r}function Fi(e,t,n){let r=Ui(e,t),i=function(e,t){for(let n=t;null!==n;n=n.l.re){let t=e.nodeList.exec(n.l.o.t);if(null!==t)return{k:t[1].length/(e.key.length+3),r:n}}return null}(e,n);return null===i&&v(`[wcs/recursion-context] "${t}" uses "**", which is bound to the depth of the row it is evaluated in; there is none here — use $getAll("${t}", []) for every depth.`),Di(e,i.k)+r}function qi(e,t,n){let r=new Set,i=new Set,s=(e,n,s)=>!(!Array.isArray(e)||0===e.length||(r.has(e)&&v(`${Wi("cycle")} "${n}" is reachable from itself: the data under "${t.l}" must be a tree.`),i.has(e)&&v(`${Wi("shared-list")} "${n}" is the same array instance as a list reached before: the data under "${t.l}" must be a tree.`),s+1>128&&v(`${Wi("depth-exceeded")} Recursion on "${t.l}.*" reached depth ${s+1} (the limit is 128).`),i.add(e),0)),o=(i,l)=>{for(let a of i){n(l,a);let i=e.o(`${Di(t,l)}.${t.key}`),u=e.read(i,a);s(u,i.t,l+1)&&(r.add(u),o(e.De(a,i).u,l+1),r.delete(u))}},l=e.o(t.l),a=e.read(l,null);s(a,t.l,0)&&(r.add(a),o(e.De(null,l).u,0))}function Bi(e,t){let n=function(e){let t=e[Li],n=[],r=new Set;for(let t=e;null!==t&&t!==Object.prototype;t=Object.getPrototypeOf(t))for(let e of Object.getOwnPropertyNames(t))!r.has(e)&&e.includes("**")&&n.push([e,Object.getOwnPropertyDescriptor(t,e)]),r.add(e);if(void 0===t)return n.length>0&&H(n[0][0]),null;(null===t||"object"!=typeof t||Array.isArray(t))&&v(`${Wi("declaration-invalid")} ${Li} must be an object mapping one anchor path to its repeating sub-path.`);let i=Object.entries(t);1!==i.length&&v(`${Wi("declaration-invalid")} ${Li} must declare exactly one anchor (it declares ${i.length}).`);let s=zi("anchor",i[0][0]),o=zi("repeat",i[0][1]),l=s.slice(0,-2),a=o.slice(0,-2),u=`.${o}`,c=new Map,h=[],d=`${l}.**`;for(let[e,t]of n){let n=e.slice(d.length);(!e.startsWith(d)||""!==n&&"."!==n[0]||n.includes("**"))&&v(`[wcs/recursion-anchor] "${e}": a recursive key is "${d}" followed by a path (the anchor is "${s}").`),(""===n||n.split(".").slice(1).some(e=>""===e))&&v(`[wcs/recursion-anchor] "${e}" needs a path after "**".`),(void 0===t.get||void 0!==t.set)&&v(`${Wi("declaration-invalid")} "${e}": a recursive key is a getter without a setter.`),c.set(n,t.get),h.push([new RegExp(`^${Hi(s)}((?:${Hi(u)})*)${Hi(n)}$`),n])}return{l:l,step:u,key:a,families:c,matchers:h,owners:new Map,nodeList:new RegExp(`^${Hi(l)}((?:${Hi(`.*.${a}`)})*)$`)}}(t),r=Mi.has(e);null!==n?(r||Ri++,Mi.set(e,n),ji.add(e),Ii.has(e)||function(e){Ii.add(e);let t=e,n=t.et;t.et=r=>{let i=Mi.get(e);if(r.t.includes("**")){let t=e.B.Ct(r.t)===r;return void(ji.has(e)||void 0===i&&t?r.getter=()=>H(r.t):t||n.call(e,r))}if(void 0!==i&&null===r.getter)for(let[e,n]of i.matchers)if(e.test(r.t)){r.getter=i.families.get(n),r.n>0&&(r.F=t.Oe++),i.owners.set(r,i.l+".**"+n);break}n.call(e,r)};let r=t.resolve;t.resolve=(t,n)=>{let i=Mi.get(e);return r.call(e,void 0!==i&&t.includes("**")?Fi(i,t,n):t,n)};let i=t.getAll;t.getAll=(n,r)=>{let s=Mi.get(e);if(void 0===s||!n.includes("**"))return i.call(e,n,r);if(void 0===r)return i.call(e,Fi(s,n,t.c));(!Array.isArray(r)||r.length>0)&&v(`${Wi("getall-form")} $getAll("${n}", indexes) with "**" takes either no indexes (this depth) or [] (every depth).`);let o=Ui(s,n),l=[];return qi(e,s,(t,n)=>{for(let r of i.call(e,Di(s,t)+o,e.W(n)))l.push(r)}),l};let s=t.pn;t.pn=(n,r,i,o)=>{let l=Mi.get(e);if(void 0===l||!n.includes("**"))return s.call(e,n,r,i,o);Array.isArray(r)||_(9,[n]),r.length>0&&v(`${Wi("setall-form")} $setAll("${n}", indexes, …) with "**" takes no partial prefix: pass [] to write every node.`),("function"==typeof i||!0===o?.spread)&&v(`${Wi("setall-form")} $setAll("${n}", [], value) with "**" takes a plain value (no mapper, no spread).`),t.Ce>0&&_(8);let a=Ui(l,n),u=a.replace(/\.\d+(?=\.|$)/g,".*");for(;u.startsWith(l.step);)u=u.slice(l.step.length);let c=l.key.split(".");(""===u||u===`.${l.key}.length`||c.some((e,t)=>u===`.${c.slice(0,t+1).join(".")}`))&&v(`${Wi("structural-write")} "${n}" writes the recursion structure itself (a node, its "${l.key}" list or that list's length, or an object on the way to it).`);for(let e of l.families.keys()){let t=e;for(;t.startsWith(l.step);)t=t.slice(l.step.length);(u===t||u.startsWith(`${t}.`))&&v(`${Wi("readonly")} "${n}" writes into the recursive getter "${l.l}.**${e}".`)}let h=[];qi(e,l,(e,t)=>h.push([e,t]));let d=0;for(let[t,n]of h)d+=s.call(e,Di(l,t)+a,e.W(n),i);return d}}(e)):r&&(Mi.delete(e),Ri--)}function Ki(e,t){if(0===Ri)return!1;let n=Mi.get(e);if(void 0===n)return!1;for(let e=t;null!==e;e=e.d){let r=n.owners.get(e);void 0!==r&&v(`${Wi("readonly")} "${t.t}" writes into the recursive getter "${r}".`)}return!1}var Gi={name:"recursion",install(){c.se=h(c.se,Bi),c.element=h(c.element,(e,t)=>{("mounting"===t||"reset"===t)&&function(e){ji.delete(e)}(e)}),c.Pe=d(f,c.Pe,Ki)}},Vi="4.0.0-rc.4",Ji=e=>e.split(".").slice(0,2).join("."),Qi=class extends Gt{static find(e){return e.querySelector?.(ee.tagNames.ssr)??null}get version(){return this.getAttribute("version")??""}get stateData(){let e=this.querySelector('script[type="application/json"]');return null===e?{}:JSON.parse(e.textContent||"{}")}get templates(){let e=new Map;for(let t of Array.from(this.children))"template"===t.localName&&e.set(t.id,t);return e}get hydrateProps(){return{}}getTemplate(e){return this.templates.get(e)??null}verifyVersion(){return Ji(this.version)===Ji(Vi)}};function Xi(e){let t=ee.tagNames.ssr;void 0===e.get(t)&&e.define(t,class extends Qi{})}var Yi=()=>ee.tagNames.ssr,Zi=Symbol.for("wcstack.ssr.snapshotBuilder"),es=()=>!0===document.documentElement?.hasAttribute("data-wcs-server"),ts=e=>document.createComment(e),ns=(e,t)=>null!==e&&8===e.nodeType&&e.data===t,rs=(e,t)=>null!==e&&8===e.nodeType&&e.data.startsWith(t),is=new WeakMap,ss=new WeakMap,os=new WeakMap,ls=new WeakSet,as=new WeakMap;function us(e,t){let n=[];for(let r=e;null!==r&&(n.push(r),r!==t);r=r.nextSibling);return n}function cs(e,t,...n){for(let n of Array.from(e.attributes))t.setAttribute(n.name,n.value);return(t.content??t).append(...n),t}var hs=e=>null===e.j?e.Ue:e.j[e.j.length-1];function ds(e,t,n){let r=[ts(null===n?"wcs-[":`wcs-[:${n}`)];for(let e of t)null===n&&r.push(ts("wcs-|")),r.push(...us(e.Ue,hs(e)));r.push(ts("wcs-]")),e.after(...r);for(let e of r)ls.add(e)}function fs(e){if(e instanceof it){ds(e.S,e.Ee,null);for(let t of e.Ee)ps(t);return}let t=e.O;null!==t&&(ds(e.X[e.X.length-1].S,[t],e.b),ps(t))}function ps(e){if(null!==e.h)for(let t of e.h)fs(t)}var ms=new Set(["script","style","template","textarea","title"]),gs="data-wcs-raw",ys=e=>ms.has(e.localName)||e.localName===Yi();function bs(e){for(let t of Array.from(e.childNodes))3===t.nodeType?""===t.data?t.replaceWith(ts("wcs-e")):null!==t.nextSibling&&3===t.nextSibling.nodeType&&t.after(ts("wcs-s")):1===t.nodeType&&!ys(t)&&bs(t)}var vs=0;function ws(e,t){let n=e.getRootNode(),r=[t];for(let e of ss.get(n)??[])e!==t&&!0===e.element?.hasAttribute("bind-component")&&r.push(e);let i=new Map;for(let e of r){let t=is.get(e);if(void 0===t)continue;let n=new Map;for(let t of e.ee.values())if(null!==t.$&&n.set(t.$.S,t.$),null!==t.L)for(let e of t.L)n.set(e.S,e);for(let t of e.ie.values())for(let e of t)if(null!==e.M)for(let t of e.M.X)n.set(t.S,e.M);let r=new Set;for(let[e,s]of t){i.set(e,s);let t=n.get(e);void 0!==t&&!r.has(t)&&e.isConnected&&(r.add(t),fs(t))}}for(let e of Array.from(n.querySelectorAll("*"))){let t=os.get(e);if(void 0!==t){let n=document.createTreeWalker(e,133,{acceptNode:e=>ls.has(e)||1===e.nodeType&&t.has(e)&&Ns(e)?2:1}),r=[];for(let e=n.nextNode();null!==e;e=n.nextNode()){let n=e.previousSibling;(3===e.nodeType?e.data.includes("{{")&&!(ys(e.parentNode)?as.has(e):t.has(n)&&rs(n,"wcs-t:"))&&(as.has(e)||t.get(e)!==e.data):!t.has(e))&&r.push(e)}for(let e of r)e.remove()}let n=Array.from(e.childNodes);ys(e)&&n.some(e=>as.has(e))&&e.setAttribute(gs,n.map(e=>as.has(e)?`{{ ${as.get(e)} }}`:8===e.nodeType?`\x3c!--${e.data}--\x3e`:e.textContent).join(""))}bs(9===n.nodeType?n.body:n);let s=document.createElement(Yi());s.setAttribute("version",Vi);let o=document.createElement("script");o.type="application/json",o.textContent=function(e){return JSON.stringify(e).replace(/[<>&\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`)}(function(e){let t={};for(let n of Object.keys(e)){if("$"===n[0])continue;let r=Object.getOwnPropertyDescriptor(e,n);void 0!==r.get||void 0!==r.set||"function"==typeof r.value||(t[n]=r.value)}return t}(t.target)),s.append(o);for(let[e,t]of i){if(!e.isConnected)continue;let n=e.parentNode;for(;null!==n&&"svg"!==n.localName&&"foreignObject"!==n.localName;)n=n.parentElement;let r="svg"===n?.localName,i=`wcs-${r?"s":"t"}${vs++}`;e.replaceWith(ts(`wcs-p:${i}`));let o=document.importNode(Et(t),!0);for(let e of Array.from(o.querySelectorAll("template")))"http://www.w3.org/2000/svg"===e.namespaceURI&&e.replaceWith(cs(e,document.createElement("template"),...e.childNodes));if(r){let e=document.createElementNS(n.namespaceURI,"svg");e.append(o),o=e}let l=document.createElement("template");l.id=i,s.append(cs(t,l,o))}e.before(s)}function _s(e){!function(e){if(null!==e.querySelector(ee.tagNames.state))for(let t of Array.from(e.querySelectorAll("input,textarea,select")))if("select"===t.localName){let e=Array.from(t.options);if(t.multiple||e.some(e=>e.hasAttribute("selected"))||e[t.selectedIndex]!==e.find(e=>!e.disabled))for(let t of e)t.toggleAttribute("selected",t.selected)}else"textarea"===t.localName?t.value!==t.defaultValue&&!t.value.includes("{{")&&!Array.from(t.childNodes).some(e=>as.has(e))&&(t.textContent=t.value):"checkbox"===t.type||"radio"===t.type?t.toggleAttribute("checked",t.checked):"password"!==t.type&&t.value!==t.defaultValue&&t.setAttribute("value",t.value)}(e);for(let t of Array.from(e.querySelectorAll(`${ee.tagNames.state}[enable-ssr]`))){if(t.hasAttribute("mount")||t.hasAttribute("bind-component")||t.previousElementSibling?.localName===Yi())continue;let e=t.engine;null!=e&&ws(t,e)}}var $s=Symbol.for("wcstack.state.ssr.impl"),ks=new Map,Ss=new WeakMap,Ns=e=>!0===c.yo?.(e),Es=e=>1===e.nodeType&&!ys(e)&&!Ns(e),As=e=>e.u.flat().concat(e.U??[]),Cs=e=>{for(let t of As(e))t.remove()};function xs(e,t,n){let r=/^wcs-\[(?::(\d+))?/.exec(e.data),i=e.previousSibling,s=e.parentNode,o=[],l=e.nextSibling;for(e.remove();null!==l&&!ns(l,"wcs-]");){let e=l.nextSibling;if(ns(l,"wcs-|"))o.push([]),l.remove();else{0===o.length&&o.push([]);let n=o[o.length-1];rs(l,"wcs-[")?e=xs(l,t,n):(n.push(l),Es(l)&&Ts(l,t))}l=e}let a={branch:void 0===r[1]?null:Number(r[1]),u:o,U:l??s.appendChild(ts("wcs-]"))},u=As(a);l=a.U.nextSibling;for(let e of u)n?.push(e),t&&kt.add(e);return t&&null!==i?ks.set(i,a):Cs(a),l}function Ts(e,t){for(let n=e.firstChild;null!==n;)rs(n,"wcs-[")?n=xs(n,t):(Es(n)&&Ts(n,t),n=n.nextSibling)}function Ps(e,t,n){let r=e=>{for(let i of Array.from(e.childNodes))if(i.parentNode===e)if(8===i.nodeType){let e=i.data;try{if("wcs-s"===e)i.remove();else if("wcs-e"===e)i.replaceWith("");else if(e.startsWith("wcs-t:")){let t=ts(`@@:${decodeURIComponent(e.slice(6))}`),n=i.nextSibling;for(;null!==n&&!ns(n,"wcs-/t");){let e=n.nextSibling;n.remove(),n=e}n?.remove(),i.replaceWith(t)}else if(e.startsWith("wcs-p:")){let n=t.querySelector(`template[id="${e.slice(6)}"]`);if(null!==n){let t=i.parentNode,r="s"===e[10]?cs(n,document.createElementNS(t.namespaceURI,"template"),...document.importNode(n.content.firstChild,!0).childNodes):document.importNode(n,!0);r.removeAttribute("id"),t.replaceChild(r,i)}}}catch{}}else 1===i.nodeType&&!ys(i)&&(Ns(i)?Ss.set(i,{ssr:t,Ae:n}):r(i))};r(e),function(e){for(let t of Array.from(e.querySelectorAll("table > tbody"))){let e=[];for(let n=t.previousSibling;null!==n&&(8===n.nodeType||Hs(n)||"template"===n.localName);n=n.previousSibling)e.unshift(n);let n=0,r=0;if(e.forEach((e,t)=>{rs(e,"wcs-[")?r++:ns(e,"wcs-]")&&--r<0&&(r=0,n=t+1)}),0===r)continue;let i=0;for(let r=t.firstChild;null!==r;r=r.nextSibling)if(rs(r,"wcs-["))i++;else if(ns(r,"wcs-]")&&0===i--){t.prepend(...e.slice(n));break}}}(e),Ts(e,n)}function Os(e){let t=Ss.get(e);if(void 0===t||(Ss.delete(e),Ps(e,t.ssr,t.Ae),!t.Ae))return null;let n=c.Ae;return c.Ae=Ds,()=>{c.Ae=n,Ls()}}function Ls(){for(let e of ks.values())Cs(e);ks.clear()}function Ms(e){let t=[];for(let n=document.createTreeWalker(e,128);n.nextNode();)t.push(n.currentNode);return t}function Is(e,t,n,r){let i=null;for(let r of e){let e=r[n];null!==e&&(""===e||t===e||t.startsWith(`${e}.`))&&(null===i||e.length>i[n].length)&&(i=r)}let s=i?.[r];if(null==s)return null;let o=i[n],l=""===o?t:t.slice(o.length+1);return""===s?l:""===l?s:`${s}.${l}`}function js(e,t,n){if(es()){if(n instanceof Array){for(let e=n.length;e-- >0;)ft(n[e])&&n.splice(e,1);let e=t;if(n.some(pt))ls.add(e);else if(e.localName.includes("-")&&!Ns(e)){let t=new Map;for(let n=document.createTreeWalker(e,133);n.nextNode();)t.set(n.currentNode,n.currentNode.data);os.set(e,t)}return}if("string"==typeof n){if(as.set(t,n),ys(t.parentNode))return;let e=ts(`wcs-t:${encodeURIComponent(n)}`),r=ts("wcs-/t");return t.before(e),void t.after(r)}let r=is.get(e);void 0===r&&is.set(e,r=new Map),r.set(t,n);let i=t.getRootNode(),s=ss.get(i);return void 0===s&&ss.set(i,s=new Set),void s.add(e)}if("string"!=typeof n&&ks.size>0){let e=ks.get(n);void 0!==e&&(ks.delete(n),ks.set(t,e))}}var Rs=e=>null!==e&&8===e.nodeType&&[ee.commentIfPrefix,ee.commentElseIfPrefix,ee.commentElsePrefix].includes(e.data),Hs=e=>3===e.nodeType&&""===e.data.trim(),Ws=e=>(ks.get(e)?.U??e).nextSibling;function zs(e,t){if(t.length!==e.on.childNodes.length)return!1;let n=e.Rn;for(let r=0;r<n.length;r++){let i=n[r],s=e.on,o=t[i[0]];for(let e=0;;){if(s=s.childNodes[i[e]],o?.nodeName!==s.nodeName)return!1;if(++e===i.length)break;o=o.firstChild;for(let t=i[e];t>0&&null!==o;t--)o=Ws(o)}e.mo[r]=o}return!0}function Ds(e,t,n){if(0===ks.size)return null;let r=t,i=0;if(!n){let e=ee.commentIfPrefix;if(!ns(t,e))for(let n=t.previousSibling;null!==n&&1!==n.nodeType&&(Rs(n)&&i++,!ns(n,e));n=n.previousSibling);for(let n=t.nextSibling;!ks.has(r)&&null!==n&&!ns(n,e)&&1!==n.nodeType;n=n.nextSibling)Rs(n)&&(r=n)}let s=ks.get(r);if(void 0===s)return null;if(!n&&s.branch!==i)return ks.delete(r),Cs(s),null;let o=s.u.shift();if(0===s.u.length&&ks.delete(r),s.U?.replaceWith(...us(t,r)),s.U=null,void 0===o)return null;let l=[];for(let e=0;e<o.length;e++){let t=ks.get(o[e]);if(l.push(o[e]),void 0!==t)for(;e<o.length&&o[e]!==t.U;)e++}if(!zs(e,l)){let n=(e.Tn?e.root:e.on).cloneNode(!0);l=e.Tn?[n]:[...n.childNodes],zs(e,l),(o[0]??s.u.find(e=>e.length>0)?.[0]??t).before(n);for(let e of o)e.remove()}return l}var Us={name:"ssr",install(){c.An=js,c.ir=Os;let e=c.element;c.element=(t,n)=>{"mounting"===n&&function(e){let t=e.element;if(!t.hasAttribute("enable-ssr")||es())return;let n=t.previousElementSibling,r=n?.localName===Yi(),i=r?n.getAttribute("version"):null,s=null===i||Ji(i)===Ji(Vi);if(s){let t=e,n=t.we;t.we=(t,r)=>"$connectedCallback"===t?void 0:n.call(e,t,r)}if(!r)return;let o=!s&&parseInt(i)<4,l=/^3\.(\d+)\.(\d+)$/.exec(i),a=null!==l&&(+l[1]-5||+l[2]-3)>=0;s||console.warn(`[@wcstack/state] <${Yi()} version="${i}"> does not match ${Vi}: its snapshot is discarded, and the page renders on the client from its own state.${o&&!a?" 3.x output keeps only the path of a text binding outside a template, so such a binding loses its filters: deploy @wcstack/server 4.0 with this client.":""}`);let u=s?n.querySelector('script[type="application/json"]'):null;if(null!==u){let t=JSON.parse(u.textContent||"{}"),n=e.target;for(let e of Object.keys(t)){let r=Object.getOwnPropertyDescriptor(n,e);void 0!==r&&(void 0!==r.get||void 0!==r.set||"function"==typeof r.value)||(n[e]=t[e])}e.hydrated=!0}let h=t.getRootNode();for(let e of Array.from(h.querySelectorAll(`[${gs}]`)))e.textContent=e.getAttribute(gs),e.removeAttribute(gs);let d=9===h.nodeType?h.body:h;o?function(e,t,n){let r=new Map,i=e=>{let t=e.parentElement;for(;null!==t&&!Ns(t);)t=t.parentElement;if(null===t)return null;let n=r.get(t);if(void 0===n){let e=i(t),s=t.querySelector(`:scope > ${ee.tagNames.state}[bind-component]`).getAttribute("bind-component");r.set(t,n=[]);for(let r of se(t.getAttribute(ee.bindAttributeName)??"")){let t=r.Je;r.ve[0]===s&&n.push([e?Is(e,t,1,0):t,r.ve.slice(1).join("."),e&&t])}}return n},s=(e,t,n)=>{let r=i(e);if(null===r)return t;let s=/^([^|]*)#m\d+\.([^|]*)$/.exec(t);if(null===s)return n?t:Is(r,t,0,1)??t;let o=s[1].replace(/#m\d+\./g,"").slice(0,-1);return r.some(e=>""===e[1]&&(e[0]===o||e[2]===o))?s[2]:Is(r,s[2],2,1)??s[2]};for(let t of Ms(e).reverse()){let e=/^@@wcs-(\w+)-start:([\s\S]*)/.exec(t.data);if(null===e)continue;let r=t.nextSibling;for(;null!==r&&!ns(r,`@@wcs-${e[1]}-end:${e[2]}`);)r=r.nextSibling;if(null!==r){for(;t.nextSibling!==r;)t.nextSibling.remove();r.remove(),t.replaceWith(..."text"===e[1]?[ts(`@@:${s(t,e[2],n)}`)]:[])}}let o=(e,n)=>{for(let r of Ms(e)){let e=/^@@wcs-(?:for|if|elseif|else):(\S+)$/.exec(r.data)?.[1],i=Array.from(t.querySelectorAll("template")).find(t=>t.id===e);if(void 0===i)continue;let l=document.importNode(i,!0),a=ee.bindAttributeName;l.removeAttribute("id"),l.setAttribute(a,l.getAttribute(a).replace(/^(\s*\w+\s*:\s*)([^\s|]+)/,(e,t,i)=>t+s(n??r,i))),o(l.content,n??r);let u=l.content.firstChild;r.replaceWith(.../^\s*elseif\s*:/.test(u?.getAttribute?.(a)??"")?l.content.childNodes:[l])}};o(e);for(let t of Array.from(e.querySelectorAll("[data-wcs-ssr-id]")))t.removeAttribute("data-wcs-ssr-id")}(d,n,a):Ps(d,n,s),n.remove(),s&&(c.Ae=Ds,queueMicrotask(()=>{Ls(),c.Ae=null}))}(t),e?.(t,n)},function(){let e=globalThis;e[$s]={build:_s,reset(){vs=0}},void 0===e[Zi]&&(e[Zi]={protocol:"wcs-ssr-snapshot",version:1,build:t=>e[$s].build(t),reset:()=>e[$s].reset()})}(),c.Eo=h(c.Eo,Xi);for(let e of Qt())Xi(e)}},Fs="__WCSTACK_DEVTOOLS_HOOK__",qs=null,Bs=new Set,Ks=(e,t,n)=>({absolutePathInfo:{pathInfo:{path:t.t},stateElement:e.element},listIndex:null===n?null:{indexes:e.W(n)}}),Gs=new WeakMap,Vs=0,Js=new WeakMap;function Qs(e){if(null===qs)return;let t=Js.get(e),n=Bs.has(e)?function(e,t){let n=new Map,r=new Set,i=(r,i,s,o,l,a)=>{if(5===r)return;let u=function(e,t){return 0===e?"textContent":2===e?`class.${t}`:3===e?`attr.${t}`:4===e?`style.${t}`:t}(r,i),c=0===o.n?null:l,h=`${(e=>{let t=Gs.get(e);return void 0===t&&Gs.set(e,t=++Vs),t})(s)}|${u}|${o.t}|${null===c?"":e.W(c).join(",")}`;if(n.has(h))return;let d=t?.get(h);n.set(h,d??{binding:{propName:u,statePathName:o.t,bindingType:a,node:s,replaceNode:s},absoluteAddress:Ks(e,o,c)})},s=e=>i(e.i,e.name,e.a,e.o,e.r,e.en()),o=e=>{if(!r.has(e)){if(r.add(e),null!==e.fe)for(let t of e.fe)s(t);if(e instanceof Ve&&null!==e.ae){let t=e.A.Ke;for(let n=0;n<t.length;n++){let r=e._?.[n];void 0!==r?s(r):i(t[n].i,t[n].name,e.ae[2*n],t[n].o,e.r,0===t[n].i?"text":"prop")}}if(null!==e.h)for(let t of e.h)l(t)}},l=e=>{if(!r.has(e))if(r.add(e),e instanceof it){i(-1,"for",e.S,e.l.o,e.l.re,"for");for(let t of e.Ee)o(t)}else null!==e.O&&o(e.O)};for(let t of e.ie.values())for(let e of t)s(e),null!==e.M&&l(e.M);for(let t of e.ee.values())if(null!==t.$&&l(t.$),null!==t.L)for(let e of t.L)l(e);return n}(e,t):new Map;if(void 0!==t)for(let[e,r]of t)n.has(e)||qs({type:"state:binding-removed",...r});for(let[e,r]of n)(void 0===t||!t.has(e))&&qs({type:"state:binding-added",...r});Js.set(e,n)}function Xs(e){let t=Ot.get(e);if(void 0===t)throw new Error("[@wcstack/state] devtools: no state tree on this root");return t}function Ys(e){let t=new Set,n=new Set,r=new Set,i=new Set;for(let s of e.B.all()){for(let e=1;e<=s.n;e++)t.add(s.f[e].t);"*"===s.s&&n.add(s.t),null!==s.getter&&r.add(s.t),null!==s.oe&&i.add(s.t)}let s=e.target;return{rootNode:e.root,element:e.element,paths:{list:t,element:n,getter:r,setter:i},commandTokenNames:new Set(Object.keys(e.commands)),eventTokenNames:new Set(e.Ne.keys()),staticDependency:new Map,dynamicDependency:new Map,watchPaths:null!==s.$watch&&"object"==typeof s.$watch?new Set(Object.keys(s.$watch)):null,keyedListPaths:null!==s.$listKeys&&"object"==typeof s.$listKeys?new Set(Object.keys(s.$listKeys)):null}}var Zs=new WeakSet,eo=new WeakMap;function to(e,t){if(("mounting"===t||"reset"===t)&&function(e){let t=(t,n)=>{if(Zs.has(t))return;Zs.add(t);let r=t.emit;t.emit=(...i)=>(null!==qs&&qs({type:"state:token-emit",kind:n,tokenName:t.name,args:i,subscriberCount:t.size,stateElement:e.element}),r.apply(t,i))};for(let n of Object.values(e.commands))t(n,"command");for(let n of e.Ne.values())t(n,"event")}(e),"connected"===t){if(Bs.has(e))return;Bs.add(e),qs?.({type:"state:element-registered",rootNode:e.root,element:e.element}),Qs(e)}else"disconnected"===t&&(Bs.delete(e),Qs(e),qs?.({type:"state:element-unregistered",rootNode:e.root,element:e.element}))}function no(e,t,n,r,i,s){if(null===qs)return;let o=Ks(e,t,0===t.n?null:n),l=eo.get(e);void 0===l&&eo.set(e,l=new Set),l.add(o),s&&qs({type:"state:write",absoluteAddress:o,value:i,oldValue:r,hasOldValue:!0})}function ro(e){if(null===qs)return;let t=eo.get(e);eo.delete(e),void 0!==t&&qs({type:"state:update-batch",addresses:t}),Qs(e)}function io(e,t,n){qs?.({type:"state:binding-apply-error",path:n.o.t,bindingType:n.en(),error:t})}!function(e){for(let t of e)g.has(t.name)||(g.add(t.name),t.install())}([pn,Bn,gr,Sr,Oi,Gi,Us,{name:"devtools",install(){c.element=h(c.element,to),c.he=h(c.he,no),c.Te=h(c.Te,ro),c.Ve=h(c.Ve,io),function(){if(typeof document>"u"||document.documentElement?.hasAttribute("data-wcs-server"))return;let e=globalThis,t=e[Fs]??(e[Fs]=function(){let e=new Map,t=new Set,n=e=>{0===t.size?e._setSink(null):e._setSink(n=>{for(let r of t)r.onEvent?.(e.id,n)})};return{version:2,sources:e,register(r){if(!e.has(r.id)){e.set(r.id,r),n(r);for(let e of t)e.onSourceRegistered?.(r)}},unregister(n){let r=e.get(n);if(void 0!==r){r._setSink(null),e.delete(n);for(let e of t)e.onSourceUnregistered?.(n)}},addListener(r){t.add(r);for(let t of e.values())n(t),r.onSourceRegistered?.(t);return()=>{if(t.delete(r))for(let t of e.values())n(t)}}}}());2!==t.version&&console.warn(`[@wcstack/state] devtools hook registry version ${t.version}, expected 2: keeping the existing one.`),t.register({id:`state:${Math.random().toString(36).slice(2,10)}`,kind:"state",packageVersion:Vi,getStateElements:()=>[...Bs].map(Ys),overlays:()=>[],keyedSubscriptions:e=>function(e){let t=[];for(let n of e.B.all()){let r=n.q,i=n.Fe?.length??0;if((null===r||0===r.size)&&0===i)continue;let s,o=0;if(null!==r)for(let e of r.values())o+=e.size;try{s=0===n.n?e.v(n,null):void 0}catch{s=void 0}t.push({path:n.t,tracked:!1,rows:o,keys:null===r?0:r.size,lists:i,lastValue:s})}return t}(Xs(e)),keys(e){let t=Xs(e).target;return Object.keys(t).filter(e=>{if(e.includes("*")||"$"===e[0])return!1;let n=Object.getOwnPropertyDescriptor(t,e);return void 0!==n.get||"function"!=typeof n.value})},read(e,t,n){let r;return Xs(e).element.createState("readonly",e=>{r=e.$resolve(t,n??[])}),r},write(e,t,n,r){Xs(e).element.createState("writable",e=>{e.$resolve(t,r??[],n)})},_setSink(e){let t=null===qs&&null!==e;qs=e,null===e&&(Js=new WeakMap),c.ot=e&&((e,t)=>qs?.({...t,stateElement:e.element})),t&&queueMicrotask(()=>{for(let e of Bs)Qs(e)})}})}()}}]),function(e=customElements){(function(){let e=globalThis;void 0===e[jt]&&(e[jt]={protocol:"wcs-binder",version:1,bind:zt})})(),Qt().includes(e)||Jt.push(new WeakRef(e));let t=ee.tagNames.state;void 0===e.get(t)&&e.define(t,class extends Vt{}),c.Eo?.(e)}();const so={route:"wcs-route",router:"wcs-router",outlet:"wcs-outlet",layout:"wcs-layout",layoutOutlet:"wcs-layout-outlet",link:"wcs-link",head:"wcs-head",guardHandler:"wcs-guard-handler"},oo=!1,lo=[".html"];function ao(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function uo(e,t){if(t&&"cause"in t)throw new Error(`[@wcstack/router] ${e}`,{cause:t.cause});throw new Error(`[@wcstack/router] ${e}`)}let co=class extends Error{fallbackPath;constructor(e,t){super(e),this.fallbackPath=t}};const ho={int:{typeName:"int",pattern:/^-?\d+$/,parse(e){if(this.pattern.test(e))return parseInt(e,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(e){if(this.pattern.test(e))return parseFloat(e)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(e){if(this.pattern.test(e))return"true"===e||"1"===e}},uuid:{typeName:"uuid",pattern:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,parse(e){if(this.pattern.test(e))return e}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(e){if(this.pattern.test(e))return e}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(e){if(!this.pattern.test(e))return;const[t,n,r]=e.split("-").map(Number),i=new Date(t,n-1,r);return i.getFullYear()===t&&i.getMonth()===n-1&&i.getDate()===r?i:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(e){if(this.pattern.test(e))return e}}};function fo(e){const t={};for(const[n,r]of new URLSearchParams(e))t[n]=r;return Object.freeze(t)}function po(e,t){const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const r of n){if(!Object.prototype.hasOwnProperty.call(t,r))return!1;if(e[r]!==t[r])return!1}return!0}const mo={static:2,param:1,"catch-all":0};let go=class extends EventTarget{_target;_parentCore=null;_path="";_name="";_isFallbackRoute=!1;_segmentInfos=[];_absoluteSegmentInfos;_paramNames;_absoluteParamNames;_weight;_absoluteWeight;_segmentCount;_params={};_typedParams={};_active=!1;_hasGuard=!1;_guardHandler=null;_guardFallbackPath="";_waitForSetGuardHandler=null;_resolveSetGuardHandler=null;_guardHandlerLoadFailed=!1;constructor(e){super(),this._target=e??this}get parentCore(){return this._parentCore}set parentCore(e){this._parentCore=e}get path(){return this._path}get name(){return this._name}get isFallbackRoute(){return this._isFallbackRoute}get isRelative(){return!this._path.startsWith("/")}get segmentInfos(){return this._segmentInfos}_checkParentCore(e,t){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&uo(`${so.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&uo(`${so.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?e(this._parentCore):t()}get absolutePath(){return this._checkParentCore(e=>{const t=e.absolutePath;return t.endsWith("/")?t+this._path:t+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(e=>[...e.absoluteSegmentInfos,...this._segmentInfos],()=>[...this._segmentInfos])),this._absoluteSegmentInfos}get params(){return this._params}get typedParams(){return this._typedParams}get active(){return this._active}get paramNames(){if(void 0===this._paramNames){const e=[];for(const t of this._segmentInfos)t.paramName&&e.push(t.paramName);this._paramNames=e}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(e=>[...e.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let e=0;for(const t of this._segmentInfos)e+=mo[t.type];this._weight=e}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(e=>e.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let e=0;for(const t of this._segmentInfos)"catch-all"!==t.type&&e++;this._segmentCount=""===this._path?0:e}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(e=>e.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(e,t={}){this._segmentInfos=[],this._absoluteSegmentInfos=void 0,this._paramNames=void 0,this._absoluteParamNames=void 0,this._weight=void 0,this._absoluteWeight=void 0,this._segmentCount=void 0,this._path=e,this._name=t.name||"",this._isFallbackRoute=t.isFallback||!1,t.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const n=e.split("/");for(let e=0;e<n.length;e++){const r=n[e];if(!(""===r&&e===n.length-1&&e>0)){if("*"===r){this._segmentInfos.push({type:"catch-all",segmentText:r,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(r.startsWith(":")){const e=r.match(/^:([^()]+)(\(([^)]+)\))?$/);let t,n="any";e?(t=e[1],e[3]&&Object.keys(ho).includes(e[3])&&(n=e[3])):t=r.substring(1),this._segmentInfos.push({type:"param",segmentText:r,paramName:t,pattern:new RegExp("^([^\\/]+)$"),paramType:n})}else""===r&&t.isIndex||this._segmentInfos.push({type:"static",segmentText:r,paramName:null,pattern:new RegExp(`^${r}$`)})}}this._hasGuard=t.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=t.guardFallback||"/",this._waitForSetGuardHandler=new Promise(e=>{this._resolveSetGuardHandler=e}))}setParams(e,t){const n=this._active;this._params=e,this._typedParams=t,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:e,typedParams:t},bubbles:!0})),n||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const e=this._active;this._params={},this._typedParams={},this._active=!1,e&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(e){for(const t of this.paramNames)if(this._params[t]!==e[t])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||uo(`${so.route} has no guardHandler.`),this._guardHandler}set guardHandler(e){this._guardHandler=e,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(e){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const t=e.path,n=e.lastPath,r=await this._guardHandler(t,n,function(e){return Object.freeze({params:Object.freeze({...e.params}),typedParams:Object.freeze({...e.typedParams}),searchParams:fo(e.search??""),routeName:e.routes[e.routes.length-1]?.name??""})}(e));if("string"==typeof r&&""!==r)throw new co("Navigation cancelled by guard.",r);if(!r)throw new co("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof r?r:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new co("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}};const yo="data-wcs-ssr",bo="data-wcs-ssr-link",vo="@@wcs-route-ph:",wo="@@wcs-route-start:",_o="@@wcs-route-end:";let $o=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=ao();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new go(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||uo(`${so.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get endMarker(){return void 0===this._endMarker&&(this._endMarker=document.createComment(`${_o}${this.absolutePath}`)),this._endMarker}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(e,t){for(this._childNodeArray=[...e],t&&(this._endMarker=t);this.firstChild;)this.removeChild(this.firstChild)}get routes(){return void 0===this._routes&&(this._routes=this.routeParentNode?this.routeParentNode.routes.concat(this):[this]),this._routes}get childIndex(){return this._childIndex}get path(){return this._core.path}get name(){return this._core.name}get isRelative(){return this._core.isRelative}get absolutePath(){return this._core.absolutePath}get segmentInfos(){return this._core.segmentInfos}get absoluteSegmentInfos(){return this._core.absoluteSegmentInfos}get params(){return this._core.params}get typedParams(){return this._core.typedParams}get paramNames(){return this._core.paramNames}get absoluteParamNames(){return this._core.absoluteParamNames}get weight(){return this._core.weight}get absoluteWeight(){return this._core.absoluteWeight}get segmentCount(){return this._core.segmentCount}get absoluteSegmentCount(){return this._core.absoluteSegmentCount}get fullpath(){return this.absolutePath}get hasGuard(){return this._core.hasGuard}get guardHandler(){return this._core.guardHandler}set guardHandler(e){this._core.guardHandler=e}setParams(e,t){this._core.setParams(e,t)}clearParams(){this._core.clearParams()}shouldChange(e){return this._core.shouldChange(e)}async guardCheck(e){return this._core.guardCheck(e)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}testAncestorNode(e){let t=this._routeParentNode;for(;t;){if(t===e)return!0;t=t.routeParentNode}return!1}initialize(e,t){if(this._initialized)return;let n;this._initialized=!0;let r=!1,i=!1;this.hasAttribute("path")?n=this.getAttribute("path")||"":this.hasAttribute("index")?(n="",r=!0):this.hasAttribute("fallback")?(n="",i=!0):uo(`${so.route} should have a "path" or "index" attribute.`),this._routerNode=e,this._routeParentNode=t;const s=t||e;s.routeChildNodes.push(this),this._childIndex=s.routeChildNodes.length-1,i&&(t&&uo(`${so.route} with fallback attribute must be a direct child of ${so.router}.`),e.fallbackRoute&&uo(`${so.router} can have only one fallback route.`),e.fallbackRoute=this),t&&(this._core.parentCore=t._core),this._core.parsePath(n,{isIndex:r,isFallback:i,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}};const ko=Symbol.for("wcstack.trustedTypes.policy"),So=Symbol.for("wcstack.trustedTypes.internal"),No="wcstack";function Eo(){const e=globalThis[ko];return null===e||"object"!=typeof e?null:e}let Ao=!1;function Co(e){const t=function(){const e=globalThis,t=e[So];if(void 0!==t)return t;const n=globalThis.trustedTypes;let r=null;if(n&&"function"==typeof n.createPolicy)try{r=n.createPolicy(No,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){"function"!=typeof Eo()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${No}". Allow it in the CSP (\`trusted-types ${No};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,e)}return e[So]=r,r}(),n=t?.createHTML;if("function"==typeof n)return n.call(t,e);if(!("trustedTypes"in globalThis))return e;const r=Eo(),i=r?.createHTML;return"function"==typeof i?(Ao||(Ao=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${No}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${No};\` in the CSP to avoid this. See docs/csp.md section 7.`)),i.call(r,e)):e}const xo=new Map;let To=class extends HTMLElement{_uuid=ao();constructor(){super()}async _loadTemplateFromSource(e){try{const t=await fetch(e);t.ok||uo(`${so.layout} failed to fetch layout from source: ${e}, status: ${t.status}`);const n=await t.text();return xo.set(e,n),n}catch(t){uo(`${so.layout} failed to load layout from source: ${e}, error: ${t}`,{cause:t})}}_loadTemplateFromDocument(e){const t=document.getElementById(`${e}`);return t&&t instanceof HTMLTemplateElement?t.innerHTML:null}async loadTemplate(){const e=this.getAttribute("src"),t=this.getAttribute("layout");e&&t&&console.warn(`${so.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(e)xo.has(e)?n.innerHTML=Co(xo.get(e)||""):n.innerHTML=Co(await this._loadTemplateFromSource(e)||"");else if(t){const e=this._loadTemplateFromDocument(t);e?n.innerHTML=Co(e):console.warn(`${so.layout} could not find template with id "${t}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&oo}get name(){return this.getAttribute("name")||""}};class Po extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||uo(`${so.outlet} has no routesNode.`),this._routesNode}set routesNode(e){this._routesNode=e}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(e){this._lastRoutes=[...e]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&oo}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const Oo=new Set(["props","states","attr",""]);function Lo(e,t,n){for(const[r,i]of Object.entries(t))switch(n){case"props":e.props={...e.props,[r]:i};break;case"states":e.states={...e.states,[r]:i};break;case"attr":null==i?e.removeAttribute(r):e.setAttribute(r,String(i));break;case"":e[r]=i}}function Mo(e,t){e.hasAttribute("data-bind")||uo(`${e.tagName} has no 'data-bind' attribute.`);const n=e.getAttribute("data-bind")||"";Oo.has(n)||uo(`${e.tagName} has invalid 'data-bind' attribute: ${n}`);const r=n,i=function(e){const t=e.tagName.toLowerCase();if(t.includes("-"))return t;const n=e.getAttribute("is");return n&&n.includes("-")?n:null}(e);i&&void 0===customElements.get(i)?customElements.whenDefined(i).then(()=>{e.isConnected&&Lo(e,t,r)}).catch(()=>{uo(`Failed to define custom element: ${i}`)}):Lo(e,t,r)}const Io=Symbol.for("wcstack.binder");function jo(){const e=globalThis[Io];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}const Ro=Symbol.for("wcstack.binder.pending"),Ho=Symbol.for("wcstack.binder.taken");function Wo(){const e=globalThis;let t=e[Ho];return void 0===t&&(t=new WeakSet,e[Ho]=t),t}function zo(e,t){const n=jo();return null===n?(function(){const e=globalThis;let t=e[Ro];return void 0===t&&(t=[],e[Ro]=t),t}().push(e),!1):(Wo().add(e),n.bind(e,t),!0)}const Do={range:!0};function Uo(e,t){for(const n of e.routeChildNodes)t.add(n.placeHolder).add(n.endMarker),Uo(n,t);return t}function Fo(e){const t=e.placeHolder,n=e.endMarker,r=null!==n.parentNode&&n.parentNode===t.parentNode&&!!(4&t.compareDocumentPosition(n)),i=r?null:Uo(e,new Set),s=[];let o=0;for(let l=t.nextSibling;null!==l&&l!==n&&(null===i||8!==l.nodeType||!/^@@(route:|wcs-route-)/.test(l.data)||i.has(l));l=l.nextSibling)s.push(l),(r||e.childNodeArray.includes(l))&&(o=s.length);return s.length=o,s}let qo=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||uo(`${so.layoutOutlet} has no layout.`),this._layout}set layout(e){this._layout=e,this.setAttribute("name",e.name)}get name(){return this.layout.name}async _initialize(){this._initializing=!0;try{this._initialized=!0,this.layout.enableShadowRoot&&!this.shadowRoot&&this.attachShadow({mode:"open"});const e=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(e.content.cloneNode(!0));for(const e of Array.from(this.layout.childNodes))this._layoutChildNodes.push(e),this.appendChild(e)}else{const t=e.content.cloneNode(!0),n=new Map;t.querySelectorAll("slot").forEach(e=>{const t=e.getAttribute("name")||"";n.has(t)?console.warn(`${so.layoutOutlet} duplicate slot name "${t}" in layout template.`):n.set(t,e)});const r=new Map,i=document.createDocumentFragment();for(const e of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(e),e instanceof Element){const t=e.getAttribute("slot")||"";if(t.length>0&&n.has(t)){r.has(t)||r.set(t,document.createDocumentFragment()),r.get(t)?.appendChild(e);continue}}i.appendChild(e)}for(const[e,t]of n){const n=r.get(e);n&&t.replaceWith(n)}const s=n.get("");s&&s.replaceWith(i),this.appendChild(t)}!function(e){if(null!==jo())for(const t of e)1===t.nodeType&&zo(t,Do)}(Array.from(this.childNodes))}finally{this._initializing=!1}}async connectedCallback(){this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected)}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(e){for(const t of this._layoutChildNodes)t instanceof Element&&(t.querySelectorAll("[data-bind]").forEach(t=>{Mo(t,e)}),t.hasAttribute("data-bind")&&Mo(t,e))}};function Bo(){return document.createElement(so.layoutOutlet)}const Ko="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function Go(e,t){(async function(e,t){let n=null,r=null;const i=t.uuid||"",s=`\n//# sourceURL=${i?`wcs-guard-handler:${i}`:"wcs-guard-handler"}\n`,o=e.text+s;let l=!1;const a=e=>{e.effectiveDirective.startsWith("script-src")&&(l=!0)};document.addEventListener("securitypolicyviolation",a);try{if("function"==typeof URL.createObjectURL){const t=new Blob([o],{type:"application/javascript"}),i=URL.createObjectURL(t);try{n=await(import(i))}catch(e){r=e}finally{URL.revokeObjectURL(i)}}if(!n){const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(o)));try{n=await(import(`data:application/javascript;base64,${t}`))}catch(e){await new Promise(e=>setTimeout(e)),uo(function(e,t,n){return n?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/router, or allow blob: in script-src. See ${Ko}`:`loadGuardHandler: failed to import guard script. data: URL error: ${e?.message??String(e)}`+(t?`. Blob URL error: ${t?.message??String(t)}`:"")+`. If this page sets a Content-Security-Policy, see ${Ko}`}(e,r,l),{cause:r??e})}}}finally{document.removeEventListener("securitypolicyviolation",a)}return n&&"function"==typeof n.default?n.default:null})(e,t).then(e=>{e?t.guardHandler=e:t.notifyGuardHandlerLoadFailed()}).catch(e=>{console.error("loadGuardHandler failed:",e),t.notifyGuardHandlerLoadFailed()})}function Vo(e,t){let n=e.get(t.absolutePath);n||(n=[]);for(const e of n)if(!t.testAncestorNode(e)){console.warn(`Duplicate route path detected: '${t.absolutePath}' (defined as '${t.path}')`);break}n.push(t),1===n.length&&e.set(t.absolutePath,n)}async function Jo(e,t,n,r){const i=n.length>0?n[n.length-1]:null,s=document.createDocumentFragment(),o=Array.from(t.childNodes);for(const t of o)if(t.nodeType===Node.ELEMENT_NODE){let o=t,l=t;const a=l.tagName.toLowerCase();if(a===so.route){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const s=document.importNode(l,!0);customElements.upgrade(s),s.appendChild(t);const a=s;a.initialize(e,i),Vo(r,a),n.push(a),o=a.placeHolder,l=a}else{if(a===so.guardHandler){if(n.length>0){const e=n[n.length-1],t=l.querySelector('script[type="module"]');t&&Go(t,e)}continue}if("template"===a){s.appendChild(l);continue}if(a===so.layout){const e=document.createDocumentFragment();for(const t of Array.from(l.childNodes))e.appendChild(t);const t=document.importNode(l,!0);customElements.upgrade(t),t.appendChild(e);const n=t,r=Bo();r.layout=n,o=r,l=t}}const u=await Jo(e,l,n,r);l.replaceChildren(),l.appendChild(u),s.appendChild(o)}else s.appendChild(t);return s}async function Qo(e){const t=new Map;return await Jo(e,e.template.content,[],t)}function Xo(e){return!1!==e.checkVisibility?.()}function Yo(e,t,n,r){const i=function(e,t,n){const r={},i={};let s=!0,o=!1,l=0,a=0;for(;l<e.absoluteSegmentInfos.length;){const t=e.absoluteSegmentInfos[l];if(t.isIndex){l++;continue}if(0===l&&""===t.segmentText&&"static"===t.type){l++;continue}const u=n[a];if(void 0===u){s=!1;break}let c=!1;if("param"===t.type){const e=t.paramType||"any",n=ho[e].parse(u);void 0!==n&&(t.paramName&&(r[t.paramName]=u,i[t.paramName]=n),c=!0)}else c=null!==t.pattern.exec(u);if(!c){s=!1;break}if("catch-all"===t.type){const e=n.slice(a).join("/");r["*"]=e,i["*"]=e,o=!0;break}l++,a++}let u=!1;return s&&(o||l===e.absoluteSegmentInfos.length&&a===n.length)&&(u=!0),u?{path:t,routes:e.routes,params:r,typedParams:i,lastPath:""}:null}(e,t,n);i&&r.push(i);for(const i of e.routeChildNodes)Yo(i,t,n,r)}function Zo(e,t){const n=e.routeChildNodes,r=[],i=t.split("/"),s=i.filter((e,t)=>!(0===t&&""===e||t===i.length-1&&""===e&&i.length>1));for(const e of n)Yo(e,t,s,r);return r.sort((e,t)=>{const n=e.routes.at(-1),r=t.routes.at(-1),i=n.absoluteSegmentCount-r.absoluteSegmentCount;if(0!==i)return-i;const s=n.absoluteWeight-r.absoluteWeight;return 0!==s?-s:n.childIndex-r.childIndex}),r.length>0?r[0]:null}let el=null,tl=null;function nl(){const e=lo;return 0===e.length?null:(el===e&&tl||(el=e,tl=new RegExp(`\\/[^/]+(?:${e.map(e=>e.replace(/\./g,"\\.")).join("|")})$`,"i")),tl)}function rl(e){let t=e||"/";t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/");const n=nl();return n&&(t=t.replace(n,"")),""===t&&(t="/"),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function il(e,t){let n=e;return""!==t&&(e===t?n="":e.startsWith(t+"/")&&(n=e.slice(t.length))),""===n?"/":n}function sl(e){let t=e||"";if(!t)return"";t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/");const n=nl();return n&&(t=t.replace(n,"")),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),"/"===t?"":t}function ol(e){if(null!==e.held)return;const t=Fo(e),n=new Set(t),r=[...t,...e.childNodeArray];let i=null;for(const s of e.childNodeArray)n.has(s)?i=s:null===s.parentNode||r.some(e=>e!==s&&e.contains(s))||(t.splice(null===i?0:t.indexOf(i)+1,0,s),n.add(s),i=s);const s=document.createDocumentFragment();!function(e,t){const n=t.map(e=>e.parentNode);for(let r=0;r<t.length;r++)t[r].parentNode===n[r]&&e.appendChild(t[r])}(s,t),s.appendChild(e.endMarker),e.held=s}function ll(e){e.clearParams(),ol(e)}function al(e,t){const n={},r={};for(const i of e.paramNames)n[i]=t.params[i],r[i]=t.typedParams[i];e.setParams(n,r);for(const t of e.childNodeArray)if(t.nodeType===Node.ELEMENT_NODE){const n=t;n.querySelectorAll("[data-bind]").forEach(t=>{Mo(t,e.typedParams)}),n.hasAttribute("data-bind")&&Mo(n,e.typedParams),n.querySelectorAll(so.layoutOutlet).forEach(t=>{t.assignParams(e.typedParams)}),n.tagName.toLowerCase()===so.layoutOutlet&&n.assignParams(e.typedParams)}}const ul=new WeakSet;function cl(e){const t=e.placeHolder;null!==t.parentNode&&(ul.has(e)||null!==e.endMarker.parentNode?(ol(e),t.after(e.held),e.held=null):t.after(...e.childNodeArray,e.endMarker),ul.add(e))}const hl=Symbol.for("wcstack.transition-runner");const dl=new WeakSet,fl="data-wcs";function pl(e,t,n){!dl.has(e)&&function(e){return e.hasAttribute(fl)||null!==e.querySelector(`[${fl}]`)}(e)&&(dl.add(e),function(e){"complete"===document.readyState?e():window.addEventListener("load",e,{once:!0})}(()=>{var r;null!==jo()||(r=e,Wo().has(r))||console.warn(`[@wcstack/router] ${t} contains ${fl} bindings that will never be applied. A binding exists only for nodes that were in the document when @wcstack/state built its bindings, and these nodes were not. They will render empty. ${n}`)}))}function ml(e){for(const t of e.childNodeArray)if(1===t.nodeType){if(t.isConnected){if(zo(t,Do))continue}else if(null!==jo())continue;pl(t,`<${t.tagName.toLowerCase()}> inside a route`,'Load @wcstack/state on this page, or render data-driven markup outside <wcs-router> — bind the router\'s `path` into state and gate the markup with <template data-wcs="if: …">. See examples/router-i18n.')}}async function gl(e,t){try{let e=null;for(const n of t.routes){const r=await n.guardCheck(t);r&&(e=null===e?r:Object.assign({},e,r))}t.data=e}catch(t){if(t instanceof co)return console.warn(`Navigation cancelled: ${t.message}. Redirecting to ${t.fallbackPath}`),queueMicrotask(()=>{e.navigate(t.fallbackPath).catch(e=>{console.error("Fallback navigation failed:",e)})}),!1;throw t}return!0}async function yl(e,t,n,r,i=""){const s=il(n,e.basename);if(e.isSameMatch(s))return e.commitNavigation({params:e.params,typedParams:e.typedParams,routeName:e.routeName,data:e.data,search:i,path:s}),!0;let o=Zo(e,s);o||(e.fallbackRoute?o={routes:[e.fallbackRoute],params:{},typedParams:{},path:s,lastPath:r}:uo(`${so.router} No route matched for path: ${s}`)),o.lastPath=r,o.search=i;const l=t.lastRoutes,a=await async function(e,t,n){if(!await gl(e,t))return!1;const r=new Set(t.routes),i=new Set(n),s=()=>{for(const e of n)r.has(e)||ll(e);const e=[];for(const n of t.routes)(e.length>0||!i.has(n)||n.shouldChange(t.params))&&(e.push(n),al(n,t));let s=!1;for(const t of e){const e=i.has(t);e&&s||cl(t),s||=e,n.length>0&&!e&&ml(t)}};let o;return 0===n.length?s():o=function(e,t,n){const r=function(e){const t=globalThis[hl];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}(e);if(null!==r)return r.run(t,{source:e,types:n});t()}("router",s),void 0!==o&&await o,!0}(e,o,l);return!!a&&(e.commitNavigation({params:o.params,typedParams:o.typedParams,routeName:o.routes[o.routes.length-1]?.name??"",data:o.data??null,search:i,path:s}),t.lastRoutes=o.routes,l.length>0&&function(e,t){if("title"===e.announcePolicy){const t=e.a11yRegion;null!==t&&(t.textContent=document.title)}if("heading"===e.focusPolicy){const e=function(e){for(const t of e){if(t.nodeType!==Node.ELEMENT_NODE)continue;const e=t;if(/^H[1-6]$/.test(e.tagName)){if(Xo(e))return e}else for(const t of e.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(Xo(t))return t}return null}(t.routes[t.routes.length-1].childNodeArray);if(null!==e)e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1"),e.focus();else{const e=document.querySelector("[autofocus]");null!==e?e.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}(e,o),!0)}function bl(){const e=window.navigation;return e?"function"!=typeof e.addEventListener||"function"!=typeof e.removeEventListener?null:e:null}function vl(e){let t=e,n="";const r=t.indexOf("#");r>=0&&(n=t.slice(r),t=t.slice(0,r));let i="";const s=t.indexOf("?");return s>=0&&(i=t.slice(s),t=t.slice(0,s)),{pathname:t,search:i,hash:n}}function wl(e){return"?"===e?"":e}function _l(e,t){let n=Object.getPrototypeOf(e);for(;null!==n;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return"function"==typeof e.get||"function"==typeof e.set;n=Object.getPrototypeOf(n)}return!1}function $l(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const kl=Object.freeze({});class Sl extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"navigateUrl",event:"wcs-router:navigate-url-changed",semantics:"state"},{name:"replaceUrl",event:"wcs-router:replace-url-changed",semantics:"state"},{name:"path",event:"wcs-router:path-changed",semantics:"state"},{name:"params",event:"wcs-router:params-changed",semantics:"state",getter:e=>e.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:e=>e.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"},{name:"data",event:"wcs-router:data-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=kl;_typedParams=kl;_searchParams=kl;_routeName="";_data=null;_hasCommitted=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((e,t)=>{this._resolveConnectedCallback=e,this._rejectConnectedCallback=t}),this._connectedCallbackPromise.catch(()=>{})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get a11yRegion(){return this._a11yRegion}get focusPolicy(){return"heading"===this.getAttribute("focus")?"heading":null}get announcePolicy(){return"title"===this.getAttribute("announce")?"title":null}_ensureA11yRegion(){if(null!==this._a11yRegion)return;const e=document.createElement("div");e.setAttribute("role","status"),e.style.position="absolute",e.style.width="1px",e.style.height="1px",e.style.overflow="hidden",e.style.clipPath="inset(50%)",e.style.whiteSpace="nowrap",this.appendChild(e),this._a11yRegion=e}_normalizePathname(e){return rl(e)}_normalizeBasename(e){return sl(e)}_joinInternalPath(e,t){const n=this._normalizeBasename(e);let r=t.startsWith("/")?t:"/"+t;return r=this._normalizePathname(r),n?"/"===r?n+"/":n+r:r}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let e=new URL(document.baseURI).pathname||"/";return"/"===e?"":this._normalizeBasename(e)}get basename(){return this._basename}_getOutlet(){const e=this.nextElementSibling;if(e&&e.matches(so.outlet))return e;const t=document.createElement(so.outlet);return this.parentNode?this.parentNode.insertBefore(t,this.nextSibling):document.body.appendChild(t),t}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||uo(`${so.router} has no outlet.`),this._outlet}get template(){return this._template||uo(`${so.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(e){const t=this._path!==e;this._path=e,t&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:e,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}get data(){return this._data}isSameMatch(e){return!!this._hasCommitted&&this._path===e}commitNavigation(e){const t=Object.freeze({...e.params}),n=Object.freeze({...e.typedParams}),r=fo(e.search),i=e.data??null,s=this._data!==i,o=!po(this._params,t),l=this._routeName!==e.routeName,a=!po(this._searchParams,r),u=this._path!==e.path;s&&(this._data=i),o&&(this._params=t,this._typedParams=n),l&&(this._routeName=e.routeName),a&&(this._searchParams=r),this._path=e.path,this._hasCommitted=!0,s&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),o&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),l&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),a&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),u&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:e.path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(e){this._fallbackRoute=e}get navigateUrl(){return this._navigateUrl}set navigateUrl(e){null!=e&&""!==e&&this._navigateUrl!==e&&(this._navigateUrl=e,this.navigate(e).catch(e=>{console.error(`${so.router} navigate failed:`,e)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(e){null!=e&&""!==e&&this._replaceUrl!==e&&(this._replaceUrl=e,this.replace(e).catch(e=>{console.error(`${so.router} replace failed:`,e)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(e){await this._performNavigation(e,!1)}async replace(e){await this._performNavigation(e,!0)}async _performNavigation(e,t){const n=vl(e),r=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,i=r+wl(n.search)+n.hash,s=bl();if(s?.navigate){const e=t?s.navigate(i,{history:"replace"}):s.navigate(i);await(e?.finished)}else{t?history.replaceState(null,"",i):history.pushState(null,"",i);const e=this._normalizePathname(r),s=this.isSameMatch(il(e,this._basename));await yl(this,this.outlet,e,this._path,wl(n.search))&&!s&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(e){return""===this._basename||e===this._basename||e.startsWith(this._basename+"/")}_onNavigateFunc(e){if(!e.canIntercept||e.hashChange||null!==e.downloadRequest)return;const t=new URL(e.destination.url),n=this._normalizePathname(t.pathname);if(!this._isOwnPath(n))return;const r=this.isSameMatch(il(n,this._basename)),i=r&&("push"===e.navigationType||"replace"===e.navigationType),s=t.search,o=this;e.intercept({handler:async()=>{try{await yl(o,o.outlet,n,o.path,s)}catch(e){throw console.error(`${so.router} applyRoute failed:`,e),e}},scroll:i?"manual":"after-transition",focusReset:r||null!==o.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const e=this._normalizePathname(window.location.pathname);this._isOwnPath(e)&&(await yl(this,this.outlet,e,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const e=$l();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const t=null!==document.querySelector("base[href]"),n=new URL(window.location.href);""!==this._basename||t||"/"===n.pathname||uo(`${so.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||uo(`${so.router} should have a <template> child element.`);const r=e?this._template.content.cloneNode(!0):null,i=await Qo(this),s=!e&&this._outlet.hasAttribute(yo);if(s||this._outlet.rootNode.appendChild(i),null!==r){const e=this._template.content;for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(r)}0===this.routeChildNodes.length&&uo(`${so.router} has no route definitions.`),e||this._ensureA11yRegion();const o=this._normalizePathname(window.location.pathname);if(e)return await this._renderForSsr(o),void(this._initialized=!0);if(s){if(await this._hydrateFromSsr(o))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(yo);const e=this._outlet.rootNode;for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(i)}await yl(this,this.outlet,o,this._path,window.location.search||""),(s||null!==jo())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(e){const t=this.outlet.rootNode,n=new Map;let r=!1;if(this._forEachRoute(e=>{n.has(e.absolutePath)?r=!0:n.set(e.absolutePath,e)}),r)return!1;if(null!==t.querySelector(so.layoutOutlet))return!1;const i=new Map,s=new Map,o=new Map,l=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT);let a=0;for(;l.nextNode();){const e=l.currentNode,t=e.data;if(a++,t.startsWith(vo)){const r=t.slice(15);if(i.has(r)||!n.has(r))return!1;i.set(r,e)}else if(t.startsWith(wo)){const r=t.slice(18);if(s.has(r)||!n.has(r))return!1;s.set(r,{comment:e,index:a})}else if(t.startsWith(_o)){const r=t.slice(16);if(o.has(r)||!n.has(r))return!1;o.set(r,{comment:e,index:a})}}if(s.size!==o.size)return!1;const u=[];for(const[e,t]of s){const n=o.get(e);if(!n)return!1;if(n.comment.parentNode!==t.comment.parentNode)return!1;if(n.index<=t.index)return!1;u.push({start:t.index,end:n.index})}for(const e of u)for(const t of u)if(e.start<t.start&&t.start<e.end&&e.end<t.end)return!1;const c=il(e,this._basename);let h=Zo(this,c);if(!h){if(null===this._fallbackRoute)return!1;h={routes:[this._fallbackRoute],params:{},typedParams:{},path:c,lastPath:this._path}}if(h.lastPath=this._path,h.routes.length!==s.size)return!1;for(const e of h.routes)if(!s.has(e.absolutePath))return!1;const d=new Set;for(const e of this.routeChildNodes)d.add(e.absolutePath);for(const e of h.routes)for(const t of e.routeChildNodes)d.add(t.absolutePath);if(i.size!==d.size)return!1;for(const e of d)if(!i.has(e))return!1;for(const[e,t]of i){const r=n.get(e);t.parentNode.replaceChild(r.placeHolder,t)}for(const e of h.routes){const t=s.get(e.absolutePath).comment,n=o.get(e.absolutePath).comment,r=[],i=new Set;let l=t.nextSibling;for(;null!==l&&l!==n;){if(l.nodeType===Node.COMMENT_NODE){const e=l.data;if(e.startsWith(wo)){const t=e.slice(18);l=o.get(t).comment.nextSibling;continue}}if(i.has(l))l=l.nextSibling;else{if(l.nodeType===Node.ELEMENT_NODE&&l.tagName.toLowerCase()===so.link){const e=l.anchorElement;null!==e&&i.add(e)}r.push(l),l=l.nextSibling}}e.adoptChildNodes(r,n)}for(const{comment:e}of s.values())e.remove();this.outlet.removeAttribute(yo);for(const e of h.routes)al(e,h);return this.outlet.lastRoutes=h.routes,!await gl(this,h)||(this.commitNavigation({params:h.params,typedParams:h.typedParams,routeName:h.routes[h.routes.length-1].name,data:h.data??null,search:window.location.search||"",path:c}),!0)}async _renderForSsr(e){const t=il(e,this._basename),n=Zo(this,t),r=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===r.length&&uo(`${so.router} No route matched for path: ${t}`),!r.some(e=>e.hasGuard)){await yl(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(e=>{e.placeHolder.data=`${vo}${e.absolutePath}`}),this.outlet.setAttribute(yo,"");for(const e of this.outlet.lastRoutes)e.placeHolder.after(document.createComment(`${wo}${e.absolutePath}`))}}_offerInitialContentToBinder(){for(const e of this.outlet.lastRoutes)for(const t of e.childNodeArray)t.nodeType===Node.ELEMENT_NODE&&t.isConnected&&zo(t,Do)}_forEachRoute(e,t=this){for(const n of t.routeChildNodes)e(n),this._forEachRoute(e,n)}async connectedCallback(){if(function(e){const t=e.constructor?.wcBindable,n=t?.inputs;if(void 0!==n)for(const t of n){const n=t.name;if(!Object.prototype.hasOwnProperty.call(e,n))continue;if(!_l(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),$l()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(e){throw this._rejectConnectedCallback?.(e),e}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(e){throw this._rejectConnectedCallback?.(e),e}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const e=bl();e&&!this._listeningNavigate&&(e.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),e||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(bl()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const Nl=["title","rel","target","download","hreflang","lang","dir"];class El extends HTMLElement{static get observedAttributes(){return["to",...Nl]}_childNodeArray=[];_uuid=ao();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const e=this.closest(so.router);if(e)return this._router=e;const t=this.getRootNode(),n=t.querySelector?.(so.router);if(n)return this._router=n;uo(`${so.link} is not connected to a router.`)}_initialize(){this.style.display="none",this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(e){return rl(e)}_joinInternalPath(e,t){const n=sl(e),r=t.startsWith("/")?t:"/"+t,i=this._normalizePathname(r);return n?"/"===i?n+"/":n+i:i}_isInternalTarget(e){return e.startsWith("/")||e.startsWith("?")}_setAnchorHref(e,t){if(this._isInternalTarget(t)){const{pathname:n,search:r,hash:i}=vl(t),s=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);e.href=s+wl(r)+i}else try{e.href=new URL(t).toString()}catch{uo(`[${so.link}] Invalid URL in 'to' attribute: ${t}`)}}connectedCallback(){$l()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const e=this.nextElementSibling;return null!==e&&"A"===e.tagName&&e.hasAttribute(bo)?e:null}_connect(){this._initialized||this._initialize();const e=this.parentNode;if(!e)return;const t=this._findSsrAnchor();let n;if(null!==t)n=t,n.removeAttribute(bo),this._childNodeArray=Array.from(n.childNodes),this._setAnchorHref(n,this._path);else{const t=this.nextSibling;n=document.createElement("a"),this._setAnchorHref(n,this._path);for(const e of Array.from(this.attributes))(e.name.startsWith("aria-")||Nl.includes(e.name))&&n.setAttribute(e.name,e.value);for(const e of this._childNodeArray)n.appendChild(e);t?e.insertBefore(n,t):e.appendChild(n)}if(this._anchorElement=n,$l())return this._updateActiveState(),void n.setAttribute(bo,"");bl()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!bl()?.navigate&&(this._onClick=async e=>{e.defaultPrevented||0===e.button&&(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||this._isInternalTarget(this._path)&&(e.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},n.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){bl()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const e=this._anchorElement;e&&(this._onClick&&(e.removeEventListener("click",this._onClick),this._onClick=void 0),e.remove(),this._anchorElement=null);for(const t of this._childNodeArray)e&&t.parentNode===e&&e.removeChild(t);this._router=null}attributeChangedCallback(e,t,n){if("to"===e&&t!==n)this._path=n||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(Nl.includes(e)){const t=this._anchorElement;t&&(null===n?t.removeAttribute(e):t.setAttribute(e,n))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const e=this._normalizePathname(new URL(window.location.href).pathname),{pathname:t}=vl(this._path),n=this._normalizePathname(this._isInternalTarget(this._path)?""===t?window.location.pathname:this._joinInternalPath(this.router.basename,t):t);this._anchorElement&&(e===n?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current","page")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const Al=[],Cl=new Map;let xl=!1;const Tl=new WeakMap;class Pl extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super(),this.style.display="none"}_initialize(){if(!this._initialized){this._initialized=!0,this._childElementArray=Array.from(this.children);for(const e of this._childElementArray)this.removeChild(e)}}connectedCallback(){this._initialize(),xl||(this._captureInitialHead(),xl=!0),Al.push(this),this._reapplyHead()}disconnectedCallback(){const e=Al.indexOf(this);-1!==e&&Al.splice(e,1),this._reapplyHead()}get childElementArray(){return this._initialized||uo("Head component is not initialized yet."),this._childElementArray}_getKey(e){const t=Tl.get(e);if(void 0!==t)return t;const n=this._computeKey(e);return Tl.set(e,n),n}_computeKey(e){const t=e.tagName.toLowerCase();if("title"===t)return"title";if("meta"===t)return`meta:${e.getAttribute("name")||""}:${e.getAttribute("property")||""}:${e.getAttribute("http-equiv")||""}:${e.hasAttribute("charset")?"charset":""}:${e.getAttribute("media")||""}`;if("link"===t)return`link:${e.getAttribute("rel")||""}:${e.getAttribute("href")||""}:${e.getAttribute("media")||""}:${e.getAttribute("hreflang")||""}`;if("base"===t)return"base";if("script"===t){const t=e.getAttribute("src")||"",n=e.getAttribute("id")||"",r=e.getAttribute("type")||"";return t||n?`script:${t}:${n}:${r}`:`script::${r}:${e.outerHTML.slice(0,100)}`}if("style"===t){const t=e.getAttribute("id")||"",n=e.getAttribute("media")||"";return t?`style:${t}:${n}`:`style::${n}:${e.outerHTML.slice(0,100)}`}return`${t}:${e.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const e=new Map;for(const t of Array.from(document.head.children)){const n=this._getKey(t);e.has(n)||e.set(n,t)}return e}_captureInitialHead(){const e=document.head;for(const t of Array.from(e.children)){const e=this._getKey(t);Cl.has(e)||Cl.set(e,t.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of Al)for(const n of t._childElementArray)e.add(this._getKey(n));for(const t of Cl.keys())e.add(t);const t=this._buildHeadElementMap();for(const n of t.keys())e.add(n);for(const n of e){let e=null;for(let t=Al.length-1;t>=0;t--){const r=Al[t];for(const t of r._childElementArray)if(this._getKey(t)===n){e=t.cloneNode(!0);break}if(e)break}!e&&Cl.has(n)&&(e=Cl.get(n).cloneNode(!0));const r=t.get(n)??null;e?(r?r.replaceWith(e):document.head.appendChild(e),t.set(n,e),zo(e)||pl(e,`<${e.tagName.toLowerCase()}> inside <${so.head}>`,`<${so.head}> reflects its children into <head> with cloneNode, so the clone is not the node that was bound. Load @wcstack/state on this page, or write the value statically here.`)):(r?.remove(),t.delete(n))}}}await void function(e=customElements){e.get(so.layout)||e.define(so.layout,To),e.get(so.layoutOutlet)||e.define(so.layoutOutlet,qo),e.get(so.outlet)||e.define(so.outlet,Po),e.get(so.route)||e.define(so.route,$o),e.get(so.router)||e.define(so.router,Sl),e.get(so.link)||e.define(so.link,El),e.get(so.head)||e.define(so.head,Pl)}(void 0);const Ol="data-fetchtarget",Ll={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let Ml=class{laneKey;policy;_ownerGeneration=0;_latestEpoch=0;_nextOperationId=1;_activeOperationId=void 0;_activeOperationIds=new Set;_queue=[];_inFlightCount=0;_terminal=new Map;_claimedOutcome=new Map;_controllers=new Map;_attempts=new Map;_withSignal;_trace;constructor(e,t,n={}){this.laneKey=e,this.policy=t,this._withSignal=n.withSignal??!1,this._trace=n.trace}get ownerGeneration(){return this._ownerGeneration}get inFlightCount(){return this._inFlightCount}get latestEpoch(){return this._latestEpoch}get activeOperationId(){return this._activeOperationId}begin(){let e;switch(this.policy){case"latest":e=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const t=this._nextOperationId++,n={operationId:t,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:e};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=t;break;case"queue":this._queue.push(n),void 0===this._activeOperationId&&(this._activeOperationId=t);break;case"overlap":this._activeOperationIds.add(t)}this._inFlightCount+=1,this._attempts.set(t,1);const r=this._makeAttempt(t,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:t,laneKey:this.laneKey,policy:this.policy}),{ticket:n,attempt:r}}retry(e){if(e.ownerGeneration!==this._ownerGeneration)return null;if(this._terminal.has(e.operationId))return null;const t=this._attempts.get(e.operationId);if(void 0===t)return null;const n=t+1;this._attempts.set(e.operationId,n),this._releaseController(e.operationId);const r=this._makeAttempt(e.operationId,n);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:e.operationId,laneKey:this.laneKey,attempt:n}),r}canCommit(e){if(e.ownerGeneration!==this._ownerGeneration)return!1;const t=this._terminal.get(e.operationId);return(void 0===t||"committing"===t)&&this._isEligible(e)}claimTerminal(e,t){return e.ownerGeneration===this._ownerGeneration&&!this._terminal.has(e.operationId)&&!!this._isEligible(e)&&(this._terminal.set(e.operationId,"committing"),this._claimedOutcome.set(e.operationId,t),!0)}claimedOutcome(e){return this._claimedOutcome.get(e.operationId)}finalize(e){const t=e.operationId,n=this._terminal.get(t);if(void 0!==n&&"committing"!==n)return;let r;r="committing"===n?this._claimedOutcome.get(t)??"stale":"stale",this._terminal.set(t,r),this._claimedOutcome.delete(t),this._releaseController(t),this._attempts.delete(t),this._inFlightCount>0&&(this._inFlightCount-=1),this._advanceBookkeeping(t),void 0!==this._trace&&("stale"===r?this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:t,laneKey:this.laneKey,outcome:r}))}signalOf(e){return this._controllers.get(e.operationId)?.signal}abort(e){this._abortController(e.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const e of this._activeOperationIds)this._abortController(e)}disposeOwner(){this._ownerGeneration+=1;for(const e of Array.from(this._controllers.keys()))this._abortController(e),this._releaseController(e);for(const e of Array.from(this._attempts.keys()))this._terminal.has(e)||this._terminal.set(e,"stale"),this._claimedOutcome.delete(e),this._attempts.delete(e),void 0!==this._trace&&this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey});this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0,this._inFlightCount=0}_makeAttempt(e,t){let n;if(this._withSignal&&"function"==typeof AbortController){const t=new AbortController;this._controllers.set(e,t),n=t.signal}return{operationId:e,attempt:t,signal:n}}_isEligible(e){switch(this.policy){case"latest":return e.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===e.operationId;case"overlap":return this._activeOperationIds.has(e.operationId)}}_advanceBookkeeping(e){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===e&&(this._activeOperationId=void 0);break;case"queue":{const t=this._queue.filter(t=>t.operationId!==e);this._queue.length=0,this._queue.push(...t),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(e)}}_abortController(e){const t=this._controllers.get(e);void 0===t||t.signal.aborted||t.abort()}_releaseController(e){this._controllers.delete(e)}};function Il(e,t){return t.every(t=>"available"===e.availability.get(t))}const jl=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let Rl=class e extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",semantics:"state",getter:e=>e.detail.value},{name:"loading",event:"wcs-fetch:loading-changed",semantics:"state"},{name:"error",event:"wcs-fetch:error",semantics:"state"},{name:"status",event:"wcs-fetch:response",semantics:"state",getter:e=>e.detail.status},{name:"objectURL",event:"wcs-fetch:response",semantics:"state",getter:e=>e.detail.objectURL},{name:"errorInfo",event:"wcs-fetch:error-info-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"}],commands:[{name:"fetch",async:!0},{name:"abort"}]};_target;_value=null;_loading=!1;_error=null;_status=0;_objectURL=null;_promise=Promise.resolve(null);_lane=new Ml("fetch","latest",{withSignal:!0});_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(e){super(),this._target=e??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._lane.disposeOwner(),null!==this._objectURL&&(this._revokeObjectURL(this._objectURL),this._objectURL=null)}get value(){return this._value}get loading(){return this._loading}get error(){return this._error}get status(){return this._status}get objectURL(){return this._objectURL}get promise(){return this._promise}get errorInfo(){return this._errorInfo}get supported(){return Il(this.platformAssessment,e.REQUIRED_CAPABILITIES)}get platformAssessment(){return function(e,t){const n=new Map,r=t=>{const n=e.get(t);return void 0===n?"unknown":n.probe()?"available":"missing"};let i=!0;for(const e of t.required){const t=r(e);n.set(e,t),"available"!==t&&(i=!1)}let s=!0;for(const e of t.optional??[]){const t=r(e);n.set(e,t),"available"!==t&&(s=!1)}const o=i?s?"ready":"degraded":"idle",l=[...t.required,...t.optional??[]],a=l.some(t=>!0===e.get(t)?.requiresSecureContext),u=l.some(t=>!0===e.get(t)?.requiresUserActivation),c=a?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",h=u?"required":"not-applicable";return{availability:n,permission:t.permission??"not-applicable",readiness:o,activity:t.activity??"inactive",preconditions:{secureContext:c,userActivation:h},epoch:t.epoch??0,lastError:t.lastError}}(jl,{required:e.REQUIRED_CAPABILITIES,optional:e.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(e,t,n,r,i){this._commitErrorInfo({code:e,phase:t,recoverable:n,message:r,...void 0===i?{}:{capabilityId:i}})}_commitErrorInfo(e){this._errorInfo!==e&&(this._errorInfo=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:e,bubbles:!0})))}_setLoading(e){this._loading=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:e,bubbles:!0}))}_setError(e){this._error!==e&&(this._error=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:e,bubbles:!0})))}_setResponse(e,t,n=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=n,this._value=e,this._status=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:e,status:t,objectURL:n},bubbles:!0}))}_createObjectURL(e){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(e):null}_revokeObjectURL(e){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(e)}abort(){this._lane.abortActive()}_commitStep(e,t){this._lane.canCommit(e)&&t()}async fetch(t,n={}){if(!t)return this._setErrorInfo("invalid-argument","start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const r=this.platformAssessment;if(!Il(r,e.REQUIRED_CAPABILITIES)){const t=e.REQUIRED_CAPABILITIES.find(e=>"available"!==r.availability.get(e));return this._setErrorInfo("capability-missing","start",!1,`Required capability "${t}" is unavailable.`,t),this._setError({message:`Required capability "${t}" is unavailable.`}),null}const i=this._doFetch(t,n);return this._promise=i,i}async _doFetch(e,t){const n=this._lane.begin(),{ticket:r,attempt:i}=n,s=i.signal;this._commitStep(r,()=>this._setLoading(!0)),this._commitStep(r,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:o="GET",body:l=null,contentType:a=null,forceText:u=!1,responseType:c="auto",timeout:h=0}=t;let d=null;h>0&&(d=setTimeout(()=>{if(!this._lane.claimTerminal(r,"timeout"))return;const e=`Request timed out after ${h}ms.`;this._commitStep(r,()=>{this._setErrorInfo("timeout","execute",!0,e),this._setError({name:"TimeoutError",message:e})}),this._commitStep(r,()=>this._setResponse(null,0)),this._commitStep(r,()=>this._setLoading(!1)),this._lane.abort(r),this._lane.finalize(r)},h));const f={...t.headers??{}};try{a&&!f["Content-Type"]&&(f["Content-Type"]=a);const t={method:o,headers:f,signal:s};"GET"!==o&&"HEAD"!==o&&null!==l&&(t.body=l);const n=await globalThis.fetch(e,t);let i=null;if("HEAD"===o);else if(n.ok)if(u)i=await n.text();else if("blob"===c)i=await n.blob();else if("arrayBuffer"===c)i=await n.arrayBuffer();else if("text"===c)i=await n.text();else if("json"===c)i=await n.json();else{const e=n.headers.get("Content-Type")||"";i=e.includes("application/json")?await n.json():await n.text()}if(!n.ok){const e=await n.text().catch(()=>""),t={status:n.status,statusText:n.statusText,body:e};return this._lane.claimTerminal(r,"error")?(this._commitStep(r,()=>{this._setErrorInfo("http-error","execute",!0,`HTTP ${n.status} ${n.statusText}`),this._setError(t)}),this._commitStep(r,()=>this._setResponse(null,n.status)),this._commitStep(r,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(r,"success"))return null;const h=i instanceof Blob?this._createObjectURL(i):null;return this._commitStep(r,()=>this._setResponse(i,n.status,h)),this._commitStep(r,()=>this._setLoading(!1)),this._value}catch(e){return e&&"AbortError"===e.name?(this._lane.claimTerminal(r,"aborted")&&this._commitStep(r,()=>this._setLoading(!1)),null):this._lane.claimTerminal(r,"error")?(this._commitStep(r,()=>{const t=String(e?.message??"Network request failed.");this._setErrorInfo("network","execute",!0,t),this._setError(e??{message:t})}),this._commitStep(r,()=>this._setResponse(null,0)),this._commitStep(r,()=>this._setLoading(!1)),null):null}finally{null!==d&&clearTimeout(d),this._lane.finalize(r)}}},Hl=!1;function Wl(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest(`[${Ol}]`);if(!n)return;const r=n.getAttribute(Ol);if(!r)return;const i=customElements.get(Ll.fetch),s=document.getElementById(r);if(!(i&&s instanceof i))return;const o=s;o.url&&(e.preventDefault(),o.fetch())}function zl(e,t){let n=Object.getPrototypeOf(e);for(;null!==n;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return"function"==typeof e.get||"function"==typeof e.set;n=Object.getPrototypeOf(n)}return!1}const Dl=Symbol.for("wcstack.trustedTypes.policy");function Ul(){const e=globalThis[Dl];return null===e||"object"!=typeof e?null:e}let Fl,ql=!1;let Bl=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Rl.wcBindable,properties:[...Rl.wcBindable.properties,{name:"trigger",event:"wcs-fetch:trigger-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"},{name:"target"},{name:"manual"},{name:"body"},{name:"responseType"},{name:"trigger"}]};static get observedAttributes(){return["url"]}_core;_body=null;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_autoPending=!1;_connectResolve=null;_lastFetchedUrl=null;_internals=null;constructor(){super(),this._internals=this._initInternals(),this._wireStates({"wcs-fetch:loading-changed":e=>({loading:!0===e}),"wcs-fetch:error":e=>({error:null!=e})}),this._core=new Rl(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const e=this.attachInternals();return e.states.add("wcs-probe"),e.states.delete("wcs-probe"),e}catch{return null}}_wireStates(e){if(null===this._internals)return;const t=this._internals.states;for(const[n,r]of Object.entries(e))this.addEventListener(n,e=>{const n=this.hasAttribute("debug-states");for(const[i,s]of Object.entries(r(e.detail))){try{s?t.add(i):t.delete(i)}catch{}n&&this.toggleAttribute(`data-wcs-state-${i}`,s)}})}get url(){return this.getAttribute("url")||""}set url(e){null==e?this.removeAttribute("url"):this.setAttribute("url",e)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(e){null==e?this.removeAttribute("method"):this.setAttribute("method",e)}get target(){return this.getAttribute("target")}set target(e){null==e?this.removeAttribute("target"):this.setAttribute("target",e)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(e){null==e?this.removeAttribute("response-type"):this.setAttribute("response-type",e)}get value(){return this._core.value}get loading(){return this._core.loading}get error(){return this._core.error}get status(){return this._core.status}get objectURL(){return this._core.objectURL}get errorInfo(){return this._core.errorInfo}get promise(){return this._core.promise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(e){e?this.setAttribute("manual",""):this.removeAttribute("manual")}get body(){return this._body}set body(e){this._body=e??null}get trigger(){return this._trigger}set trigger(e){if(e){if(!this.url)return;this._trigger=!0,this.fetch().finally(()=>{this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-fetch:trigger-changed",{detail:!1,bubbles:!0}))})}}_collectHeaders(){const e={},t=this.querySelectorAll(Ll.fetchHeader);for(const n of t){const t=n.headerName,r=n.headerValue;t&&(e[t]=r)}return e}_isNativeBodyInit(e){return e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||e instanceof ArrayBuffer||ArrayBuffer.isView(e)}_collectBody(e){if(null!==e)return"string"==typeof e||this._isNativeBodyInit(e)?{body:e,contentType:null}:{body:JSON.stringify(e),contentType:"application/json"};const t=this.querySelector(Ll.fetchBody);return t?{body:t.bodyContent||null,contentType:t.contentType}:{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const e=this._connectResolve;this._connectResolve=null;const t=this.url;this.isConnected&&!this.manual&&t&&t!==this._lastFetchedUrl?this.fetch().finally(()=>e?.()):e?.()}))}async fetch(){this._lastFetchedUrl=this.url;const e=this._collectHeaders(),t=this._body;this._body=null;const{body:n,contentType:r}=this._collectBody(t);n instanceof FormData&&Object.keys(e).some(e=>"content-type"===e.toLowerCase())&&console.warn("[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. This drops the multipart boundary the browser adds automatically; remove the Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.");const i=await this._core.fetch(this.url,{method:this.method,headers:e,body:n,contentType:r,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==i){const e=document.getElementById(this.target);e&&function(e,t){try{e.innerHTML=function(e){if("string"!=typeof e)return e;const t=Ul(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(t)}catch(e){if(function(){if(void 0!==Fl)return Fl;if(!("trustedTypes"in globalThis))return Fl=!1,Fl;try{document.createElement("div").innerHTML="<i></i>",Fl=!1}catch{Fl=!0}return Fl}())return void function(){if(ql)return;ql=!0;const e="function"==typeof Ul()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/fetch deliberately does not pass responses through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/fetch] The "target" HTML replace mode was blocked by Trusted Types (require-trusted-types-for 'script'). ${e}\nInstall a sanitizing policy before the first fetch:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr drop "target" and bind the response through @wcstack/state. See docs/csp.md section 7.`)}();throw e}}(e,i)}return i}attributeChangedCallback(e,t,n){"url"===e&&this._scheduleAutoFetch()}connectedCallback(){!function(e){const t=e.constructor?.wcBindable,n=t?.inputs;if(void 0!==n)for(const t of n){const n=t.name;if(!Object.prototype.hasOwnProperty.call(e,n))continue;if(!zl(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this.style.display="none",Hl||(Hl=!0,document.addEventListener("click",Wl)),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(e=>{this._connectResolve=e})),this._scheduleAutoFetch()}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}};class Kl extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class Gl extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}let Vl=class extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;get target(){return this.getAttribute("target")||""}set target(e){this.setAttribute("target",e)}get root(){return this.getAttribute("root")}set root(e){null===e?this.removeAttribute("root"):this.setAttribute("root",e)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(e){this.setAttribute("root-margin",e)}get threshold(){const e=Number(this.getAttribute("threshold")??"0");return Number.isFinite(e)?e:0}set threshold(e){this.setAttribute("threshold",String(e))}get disabled(){return this.hasAttribute("disabled")}set disabled(e){e?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(e){e?this.setAttribute("once",""):this.removeAttribute("once")}connectedCallback(){this._observe()}disconnectedCallback(){this._disconnectObserver()}attributeChangedCallback(){this.isConnected&&this._observe()}_observe(){this._disconnectObserver(),this._done||this.disabled||!this.target||"undefined"==typeof IntersectionObserver||(this._observer=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&this._triggerFetch()},{root:this._resolveRoot(),rootMargin:this.rootMargin,threshold:this.threshold}),this._observer.observe(this))}_disconnectObserver(){this._observer&&(this._observer.disconnect(),this._observer=null)}_resolveRoot(){return this.root&&document.getElementById(this.root)||null}_triggerFetch(){const e=document.getElementById(this.target);e instanceof Bl&&(e.loading||(e.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(e=customElements){e.get(Ll.fetch)||e.define(Ll.fetch,Bl),e.get(Ll.fetchHeader)||e.define(Ll.fetchHeader,Kl),e.get(Ll.fetchBody)||e.define(Ll.fetchBody,Gl),e.get(Ll.infiniteScroll)||e.define(Ll.infiniteScroll,Vl)}(void 0);const Jl="data-storagetarget",Ql={storage:"wcs-storage"},Xl="wcs-storage:value-changed",Yl="wcs-storage:loading-changed",Zl="wcs-storage:error",ea="wcs-storage:error-info-changed",ta="wcs-storage:trigger-changed";let na=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:Xl,semantics:"state",getter:e=>e.detail},{name:"loading",event:Yl,semantics:"state"},{name:"error",event:Zl,semantics:"state"},{name:"errorInfo",event:ea,semantics:"state"}],inputs:[{name:"key"},{name:"type"}],commands:[{name:"load"},{name:"save"},{name:"remove"}]};_target;_value=null;_loading=!1;_error=null;_errorInfo=null;_key="";_type="local";_storageListener=null;_gen=0;_ready=Promise.resolve();constructor(e){super(),this._target=e??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stopSync()}get value(){return this._value}set value(e){Object.is(e,this._value)||this._setValue(e)}get loading(){return this._loading}get error(){return this._error}get errorInfo(){return this._errorInfo}get key(){return this._key}set key(e){this._key=String(e)}get type(){return this._type}set type(e){"local"===e||"session"===e?this._type=e:this._setError({operation:"type",message:`Invalid storage type: "${e}". Must be "local" or "session".`})}_getStorage(){return"session"===this._type?sessionStorage:localStorage}_setLoading(e){this._loading=e,this._target.dispatchEvent(new CustomEvent(Yl,{detail:e,bubbles:!0}))}_setError(e,t){this._error!==e&&(this._error=e,this._commitErrorInfo(null===e?null:function(e,t){return void 0===t?{code:"invalid-argument",phase:"start",recoverable:!1,message:e.message}:"QuotaExceededError"===t?{code:"quota-exceeded",phase:"execute",recoverable:!0,message:e.message}:"SecurityError"===t?{code:"not-allowed",phase:"execute",recoverable:!1,message:e.message}:{code:"storage-error",phase:"execute",recoverable:!0,message:e.message}}(e,t)),this._target.dispatchEvent(new CustomEvent(Zl,{detail:e,bubbles:!0})))}_commitErrorInfo(e){this._errorInfo=e,this._target.dispatchEvent(new CustomEvent(ea,{detail:e,bubbles:!0}))}_toStorageError(e,t){return{operation:e,message:t instanceof Error?t.message:String(t)}}_errName(e){return e instanceof Error?e.name:""}_setValue(e){this._value=e,this._target.dispatchEvent(new CustomEvent(Xl,{detail:e,bubbles:!0}))}load(){if(!this._key)return this._setError({operation:"load",message:"key is required."}),null;this._setLoading(!0),this._setError(null);try{const e=this._getStorage().getItem(this._key);if(null===e)this._setValue(null);else try{this._setValue(JSON.parse(e))}catch{this._setValue(e)}return this._setLoading(!1),this._value}catch(e){return this._setError(this._toStorageError("load",e),this._errName(e)),this._setLoading(!1),null}}save(e){if(this._key){this._setLoading(!0),this._setError(null);try{const t=this._getStorage();null==e?(t.removeItem(this._key),this._setValue(null)):"string"==typeof e?(t.setItem(this._key,e),this._setValue(e)):(t.setItem(this._key,JSON.stringify(e)),this._setValue(e)),this._setLoading(!1)}catch(e){this._setError(this._toStorageError("save",e),this._errName(e)),this._setLoading(!1)}}else this._setError({operation:"save",message:"key is required."})}remove(){if(this._key){this._setLoading(!0),this._setError(null);try{this._getStorage().removeItem(this._key),this._setValue(null),this._setLoading(!1)}catch(e){this._setError(this._toStorageError("remove",e),this._errName(e)),this._setLoading(!1)}}else this._setError({operation:"remove",message:"key is required."})}startSync(){if(this._storageListener)return;const e=++this._gen;this._storageListener=t=>{if(e===this._gen&&t.key===this._key&&"session"!==this._type)if(this._setError(null),null===t.newValue)this._setValue(null);else try{this._setValue(JSON.parse(t.newValue))}catch{this._setValue(t.newValue)}},globalThis.addEventListener("storage",this._storageListener)}stopSync(){this._storageListener&&(globalThis.removeEventListener("storage",this._storageListener),this._storageListener=null)}},ra=!1;function ia(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest(`[${Jl}]`);if(!n)return;const r=n.getAttribute(Jl);if(!r)return;const i=customElements.get(Ql.storage),s=document.getElementById(r);i&&s instanceof i&&(e.preventDefault(),s.save())}function sa(e,t){let n=Object.getPrototypeOf(e);for(;null!==n;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return"function"==typeof e.get||"function"==typeof e.set;n=Object.getPrototypeOf(n)}return!1}let oa=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...na.wcBindable,properties:[...na.wcBindable.properties,{name:"trigger",event:ta,semantics:"state"}],inputs:[{name:"key"},{name:"type"},{name:"value"},{name:"manual"},{name:"trigger"}]};static get observedAttributes(){return["key","type"]}_core;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_internals=null;constructor(){super(),this._core=new na(this),this._internals=this._initInternals(),this._wireStates({[Yl]:e=>({loading:!0===e}),[Zl]:e=>({error:null!=e})})}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const e=this.attachInternals();return e.states.add("wcs-probe"),e.states.delete("wcs-probe"),e}catch{return null}}_wireStates(e){if(null===this._internals)return;const t=this._internals.states;for(const[n,r]of Object.entries(e))this.addEventListener(n,e=>{const n=this.hasAttribute("debug-states");for(const[i,s]of Object.entries(r(e.detail))){try{s?t.add(i):t.delete(i)}catch{}n&&this.toggleAttribute(`data-wcs-state-${i}`,s)}})}_syncCore(){this._core.key=this.key,this._core.type=this.type}get key(){return this.getAttribute("key")||""}set key(e){this.setAttribute("key",e)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(e){this.setAttribute("type",e)}get value(){return this._core.value}set value(e){this.manual?this._core.value=e:(this._syncCore(),this._core.save(e))}get loading(){return this._core.loading}get error(){return this._core.error}get errorInfo(){return this._core.errorInfo}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(e){e?this.setAttribute("manual",""):this.removeAttribute("manual")}get trigger(){return this._trigger}set trigger(e){if(e){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(ta,{detail:!1,bubbles:!0}))}}}load(){return this._syncCore(),this._core.load()}save(){this._syncCore(),this._core.save(this._core.value)}remove(){this._syncCore(),this._core.remove()}attributeChangedCallback(e,t,n){this.isConnected&&("key"===e&&(this._syncCore(),n&&!this.manual&&this.load()),"type"===e&&this._syncCore())}connectedCallback(){!function(e){const t=e.constructor?.wcBindable,n=t?.inputs;if(void 0!==n)for(const t of n){const n=t.name;if(!Object.prototype.hasOwnProperty.call(e,n))continue;if(!sa(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this.style.display="none",ra||(ra=!0,document.addEventListener("click",ia)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(e=customElements){e.get(Ql.storage)||e.define(Ql.storage,oa)}(void 0);const la="*",aa="vanilla",ua={loaders:{[aa]:{postfix:".js",loader:async function(e){return(await(import(`${e}`))).default}},[la]:aa},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function ca(e){if(e.startsWith("@components/")){if(e.endsWith("/")){const t=e.slice(12,e.length-1),[n,r]=t.split("|",2);if(""===n)throw new Error("Invalid importmap key: "+e);return{key:e,prefix:n.replaceAll("/","-").toLowerCase(),loaderKey:r??null,isNameSpaced:!0}}{const t=e.slice(12),[n,r]=t.split("|",2),[i,s]=(r??"").split(",",2);if(""===n)throw new Error("Invalid importmap key: "+e);return{key:e,tagName:n.replaceAll("/","-").toLowerCase(),loaderKey:i||null,extends:s||null,isNameSpaced:!1}}}return null}function ha(e,t,n){let r;if(null===t||t===la||""===t){let t=null;const i=[];for(const[e,t]of Object.entries(n)){if(e===la)continue;const r="string"==typeof t?n[t]:t;"string"!=typeof r&&i.push(r)}i.sort((e,t)=>t.postfix.length-e.postfix.length);for(const n of i)if(e.endsWith(n.postfix)){t=n;break}t?r=t:(r=n[la],"string"==typeof r&&(r=n[r]))}else if(r=n[t],!r)throw new Error("Loader not found: "+t);if("string"==typeof r)throw new Error("Loader redirection is not supported here");return r}const da=new Set,fa=new Map;let pa=new WeakMap;function ma(e){if(e===globalThis.customElements)return fa;let t=pa.get(e);return void 0===t&&(t=new Map,pa.set(e,t)),t}const ga=new Map;async function ya(e,t,n){try{if(customElements.get(t))return;const r=await n.loader(e.key);if(null!==r){let n=e.extends;if(null===n&&(n=function(e){for(const[t,n]of ga)if(e.prototype instanceof t)return n;return null}(r)),customElements.get(t))return;null===n?customElements.define(t,r):customElements.define(t,r,{extends:n})}}catch(e){da.has(t)||(console.error(`Failed to eager load component '${t}':`,e),da.add(t))}}function ba(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined||"function"!=typeof t.define?null:t}function va(e){const t=e.tagName.toLowerCase();let n,r;if(t.includes("-"))n=t,r=null;else{const i=e.getAttribute("is");if(null===i)throw new Error("Custom element without a dash or 'is' attribute found: "+t);if(!i.includes("-"))throw new Error("Custom element 'is' attribute without a dash found: "+t);n=i,r=t}return{name:n,extends:r}}"undefined"!=typeof window&&[[HTMLButtonElement,"button"],[HTMLInputElement,"input"],[HTMLAnchorElement,"a"],[HTMLImageElement,"img"],[HTMLDivElement,"div"],[HTMLSpanElement,"span"],[HTMLParagraphElement,"p"],[HTMLUListElement,"ul"],[HTMLOListElement,"ol"],[HTMLLIElement,"li"],[HTMLTableElement,"table"],[HTMLFormElement,"form"],[HTMLLabelElement,"label"],[HTMLSelectElement,"select"],[HTMLTextAreaElement,"textarea"],[HTMLHeadingElement,"h1"],[HTMLQuoteElement,"blockquote"],[HTMLPreElement,"pre"],[HTMLBRElement,"br"],[HTMLHRElement,"hr"],[HTMLModElement,"ins"],[HTMLTableCaptionElement,"caption"],[HTMLTableColElement,"col"],[HTMLTableSectionElement,"tbody"],[HTMLTableRowElement,"tr"],[HTMLTableCellElement,"td"],[HTMLFieldSetElement,"fieldset"],[HTMLLegendElement,"legend"],[HTMLDListElement,"dl"],[HTMLOptGroupElement,"optgroup"],[HTMLOptionElement,"option"],[HTMLStyleElement,"style"],[HTMLScriptElement,"script"],[HTMLTemplateElement,"template"],[HTMLCanvasElement,"canvas"],[HTMLIFrameElement,"iframe"],[HTMLObjectElement,"object"],[HTMLEmbedElement,"embed"],[HTMLVideoElement,"video"],[HTMLAudioElement,"audio"],[HTMLTrackElement,"track"],[HTMLMapElement,"map"],[HTMLAreaElement,"area"],[HTMLSourceElement,"source"],[HTMLParamElement,"param"],[HTMLMeterElement,"meter"],[HTMLProgressElement,"progress"],[HTMLOutputElement,"output"],[HTMLDetailsElement,"details"],[HTMLDialogElement,"dialog"],[HTMLMenuElement,"menu"],[HTMLSlotElement,"slot"],[HTMLTimeElement,"time"],[HTMLDataElement,"data"],[HTMLPictureElement,"picture"]].forEach(([e,t])=>{void 0!==e&&ga.set(e,t)});const wa=new WeakSet,_a=new WeakSet;async function $a(e,t,n){e.shadowRoot&&(wa.has(e)||await async function(e,t,n){wa.add(e),await Ea(e.shadowRoot,t,n)}(e,t,n))}async function ka(e,t,n,r){const i=function(e,t){for(const[n,r]of Object.entries(t))if(e.startsWith(n+"-"))return r;return null}(e.name,n);if(null===i)throw new Error("No matching namespace found for lazy loaded component: "+e.name);const s=ma(r),o=s.get(e.name);if(void 0!==o)return void await o;const l=async function(e,t,n,r){try{let i;try{i=ha("",n.loaderKey,t.loaders)}catch(t){throw new Error("Loader redirection is not supported for lazy loaded components: "+e.name)}const s=e.name.slice(n.prefix.length+1);if(""===s)throw new Error("Invalid component name for lazy loaded component: "+e.name);const o=n.key+s+i.postfix;if(r.get(e.name))return;const l=await i.loader(o);if(null===l)throw new Error("Loader returned null for component: "+e.name);if(r.get(e.name))return;null===e.extends?r.define(e.name,l):r.define(e.name,l,{extends:e.extends})}catch(t){console.error(`Failed to lazy load component '${e.name}':`,t),da.add(e.name)}}(e,t,i,r);s.set(e.name,l);try{await l}finally{s.delete(e.name)}}async function Sa(e,t,n,r){const i=[],s=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_ELEMENT,e=>(e=>(e instanceof Element&&(e.tagName.includes("-")||e.getAttribute("is")?.includes("-")))??!1)(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP);for(;s.nextNode();)i.push(s.currentNode);const o=[],l=new Set;for(const e of i){const i=va(e);void 0===r.get(i.name)?(_a.has(e)||(_a.add(e),r.whenDefined(i.name).then(async()=>{await $a(e,t,n)})),l.has(i.name)||da.has(i.name)||(l.add(i.name),o.push(i))):await $a(e,t,n)}let a=0;for(const e of o)await ka(e,t,n,r),a++;return a}async function Na(e,t,n,r){for(;await Sa(e,t,n,r)>0;);}async function Ea(e,t,n){if(0===Object.keys(n).length)return null;const r=function(e=null){if(null!=e){const t=e.customElementRegistry;if(null===t)return null;if(void 0!==t)return ba(t)}return ba(globalThis.customElements)}(e);if(null===r)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await Na(e,t,n,r)}catch(e){throw new Error("Failed to lazy load components: "+e)}if(!t.observable)return null;const i=new MutationObserver(async()=>{try{await Na(e,t,n,r)}catch(e){console.error("Failed to lazy load components: "+e)}});return i.observe(e,{childList:!0,subtree:!0}),i}class Aa extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),Aa._instance)throw new Error(`${ua.tagNames.autoloader} can only be instantiated once.`);Aa._instance=this;const e=function(){const e={imports:{}};return document.querySelectorAll('script[type="importmap"]').forEach(t=>{try{const n=JSON.parse(t.innerHTML);n.imports&&(e.imports=Object.assign(e.imports,n.imports))}catch(e){throw new Error("Failed to parse importmap JSON: "+e)}}),Object.keys(e.imports).length>0?e:null}();if(e){const{prefixMap:t,loadMap:n}=function(e){const t={},n={};for(const[r,i]of Object.entries(e.imports)){const e=ca(r);null!==e&&(e.isNameSpaced?t[e.prefix]=e:n[e.tagName]=e)}return{prefixMap:t,loadMap:n}}(e);this._prefixMap=t,async function(e,t){const n=[];for(const[r,i]of Object.entries(e)){let s;try{s=ha(i.key,i.loaderKey,t)}catch(e){throw new Error("Loader redirection is not supported for eager loaded components: "+r)}n.push(ya(i,r,s))}await Promise.all(n)}(n,ua.loaders).catch(e=>{console.error("Failed to eager load components:",e)})}}async connectedCallback(){this._initialized||(this._initialized=!0,this._prefixMap&&("loading"===document.readyState&&await new Promise(e=>document.addEventListener("DOMContentLoaded",()=>e(),{once:!0})),this._observer=await Ea(document,ua,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,Aa._instance===this&&(Aa._instance=null)}}!function(e=customElements){e.get(ua.tagNames.autoloader)||e.define(ua.tagNames.autoloader,Aa)}(void 0);
|
|
2
2
|
//# sourceMappingURL=auto.min.js.map
|