wcstack 4.0.0-rc.5 → 4.0.0-rc.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auto.min.js +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.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 q=0;function F(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.Vt=0,this.fn=!1,this.Ht=!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.Vn=[],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.Hn===t)){n.push({getter:e,Hn: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=F(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=++q;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.Vn: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};F(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.Ht=!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,Hn: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.Vo(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.Ho(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.Vn.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?F(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.Vt;this.Vt=0;let t=0;if(!this.Ht||this.Ut?this._n():e>0?t=e:1===(t=++this.M)&&setTimeout(this._n,0),this.Ht=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.Ve(),this.yt&&(this.Vt=t+1))});void 0!==s&&s.then(void 0,e=>console.error(e))}}finally{this.dn=!1}this.Ht=this.Ut=!1,this.Ve(),c.Te?.(this),e>0&&this.yt&&(this.Vt=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=F(this.Ie,e.t,K);null!==t&&n.push(this.W(t))}bn(){this.Ie="function"==typeof this.target.$renderedCallback?new Map:null}Ve(){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.He?.(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.V;(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.V;return null===r||"state"===r||"auto"===r&&void 0!==e.v(t.o,n)?t.H: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()):Fe(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)}Yo(){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)}},qe=e=>"textContent"===e||"innerText"===e||"innerHTML"===e;function Fe(e,t,n,r){switch(e){case 0:return void(t.data=null==r?"":String(r));case 1:return void(qe(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}Ho(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.Go,y=e.Ie,b=t.Jo?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].H}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.H&&(Fe(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)),l=null===i?c.Xo?.(n,s):null;l||(null===i&&Ie(1202,n,`command.${s}`),i.commands.has(s)||_(1203,[n.localName,s]));let a=new WeakRef(n),u=o.subscribe((...e)=>{let t=a.deref();if(void 0!==t)return t.isConnected?l?l(t,e):t[s](...e):void 0;u()});null!==r&&(r.St??=[]).push(u)}(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,V: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.Qo?.(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.Yo())}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,H:t,Nn:null,A:null,X:null,I:null,xt:null,ke:!1,V: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&&qe(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,V:r,z:i}}(e,t.tn),o=r.localName.includes("-"),l=t.ve,a=t.Je;if("event"===t.w){if(null!==s.V&&"none"!==s.V&&_(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,V:s.V,z:s.z};if("radio"===t.w||"checkbox"===t.w)return("element"===s.V||"auto"===s.V)&&_(37,[t.w,s.V]),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.V=null,c.name=e,"class"===t?(c.i=2,c.H=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,Zo: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),H:""}}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,Zo: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,Go:p,Tn:u,Jo: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.V)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.Ve()}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.Ve()}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)}}Vo(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)}))}},qt=0,Ft=new WeakMap;function Bt(e,t=e.getRootNode()){Ft.set(t,[...Ft.get(t)??[],e].filter((e,t,n)=>e.isConnected&&n.lastIndexOf(e)===t))}function Kt(e){let t=Ft.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?Ft.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.He=!1,this.H=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.He&&_(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.H=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//${++qt}`);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.H?Promise.resolve(this.H):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.H=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.He=!this._,this.kt(e)}}So(){this._=!0,this.rn()}kt(e,t){this.Ve(this._?50:49,e),this.rn(),t?this.sn():this.wo(e)}Ve(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.Ve(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}).${!e.includes("-")&&t.startsWith("command.")?" A native element's command needs the add-on @wcstack/state/features/native-commands.":""}`,1203:(e,t)=>`<${e}> declares no command "${t}".`,1204:(e,t)=>`<${e}> declares no property "${t}".`,1205:(e,t,n)=>`<${e}> has no command "${t}" (a native <${e}>'s commands: ${n}).`,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 qn=[["$streams","$stream"],["$updatedCallback","$renderedCallback"]],Fn={$trackDependency:"$dependOn",$untrackDependency:"$untracked"},Bn={name:"diagnostics",install(){c.Ao=Cn,c.Fo=Sn,c.go=Rn,c.detail=Un,c.He=h(c.He,zn);let e=c.se;c.se=(t,n)=>{(function(e){void 0!==e.$scan&&_(1);for(let[t,n]of qn)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(Fn,t)?_(1701,[t,Fn[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}er(){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}}tr(){for(let e of this.entries)this.start(e,!0)}nr(){for(let e of this.entries)e.at=!1,e.Y?.abort(),e.Y=null}or(){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.H),this.set(sr,e.name,null),this.set(ir,e.name,"active"),this.ir(e,s,n)}async ir(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.H;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,H: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.nr()),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.or();n.Xe&&(n.D.er(),n.Pt.tr())}}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 qr(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 Fr=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),Fr.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.sr?.(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,qr),c.it=d(m,c.it,Gr),c.it=d(m,c.it,Pi),c.Qo=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:Fr.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 qi(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 Fi(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("**")?qi(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,qi(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 Fi(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=[];Fi(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.5",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.sr=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)}},qs="__WCSTACK_DEVTOOLS_HOOK__",Fs=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===Fs)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)||Fs({type:"state:binding-removed",...r});for(let[e,r]of n)(void 0===t||!t.has(e))&&Fs({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!==Fs&&Fs({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),Fs?.({type:"state:element-registered",rootNode:e.root,element:e.element}),Qs(e)}else"disconnected"===t&&(Bs.delete(e),Qs(e),Fs?.({type:"state:element-unregistered",rootNode:e.root,element:e.element}))}function no(e,t,n,r,i,s){if(null===Fs)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&&Fs({type:"state:write",absoluteAddress:o,value:i,oldValue:r,hasOldValue:!0})}function ro(e){if(null===Fs)return;let t=eo.get(e);eo.delete(e),void 0!==t&&Fs({type:"state:update-batch",addresses:t}),Qs(e)}function io(e,t,n){Fs?.({type:"state:binding-apply-error",path:n.o.t,bindingType:n.en(),error:t})}var so={"*":["focus","blur","click","scrollIntoView","showPopover","hidePopover","togglePopover"],dialog:["show","showModal","close","requestClose"],form:["requestSubmit","checkValidity","reportValidity"],input:["select","setSelectionRange","showPicker","setCustomValidity","checkValidity","reportValidity"],textarea:["select","setSelectionRange","setCustomValidity","checkValidity","reportValidity"],select:["showPicker","setCustomValidity","checkValidity","reportValidity"],audio:["play","pause","load"],video:["play","pause","load"]};function oo(e,t){let n=e.localName;if(n.includes("-"))return null;let r=(e=>[...so["*"],...Object.hasOwn(so,e)?so[e]:[]])(n);return r.includes(t)||_(1205,[n,t,r.join(", ")],t,r),(e,n)=>e[t](...n[0]instanceof Event?[]:n)}!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.He=h(c.He,io),function(){if(typeof document>"u"||document.documentElement?.hasAttribute("data-wcs-server"))return;let e=globalThis,t=e[qs]??(e[qs]=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===Fs&&null!==e;Fs=e,null===e&&(Js=new WeakMap),c.ot=e&&((e,t)=>Fs?.({...t,stateElement:e.element})),t&&queueMicrotask(()=>{for(let e of Bs)Qs(e)})}})}()}},{name:"native-commands",install(){c.Xo=oo}}]),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 lo={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"},ao=!1,uo=[".html"];function co(){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 ho(e,t){if(t&&"cause"in t)throw new Error(`[@wcstack/router] ${e}`,{cause:t.cause});throw new Error(`[@wcstack/router] ${e}`)}let fo=class extends Error{fallbackPath;constructor(e,t){super(e),this.fallbackPath=t}};const po={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 mo(e){const t={};for(const[n,r]of new URLSearchParams(e))t[n]=r;return Object.freeze(t)}function go(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 yo={static:2,param:1,"catch-all":0};let bo=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&&ho(`${lo.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&ho(`${lo.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+=yo[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(po).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||ho(`${lo.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:mo(e.search??""),routeName:e.routes[e.routes.length-1]?.name??""})}(e));if("string"==typeof r&&""!==r)throw new fo("Navigation cancelled by guard.",r);if(!r)throw new fo("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof r?r:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new fo("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}};const vo="data-wcs-ssr",wo="data-wcs-ssr-link",_o="@@wcs-route-ph:",$o="@@wcs-route-start:",ko="@@wcs-route-end:";let So=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=co();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new bo(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||ho(`${lo.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(`${ko}${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):ho(`${lo.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&&ho(`${lo.route} with fallback attribute must be a direct child of ${lo.router}.`),e.fallbackRoute&&ho(`${lo.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 No=Symbol.for("wcstack.trustedTypes.policy"),Eo=Symbol.for("wcstack.trustedTypes.internal"),Ao="wcstack";function Co(){const e=globalThis[No];return null===e||"object"!=typeof e?null:e}let xo=!1;function To(e){const t=function(){const e=globalThis,t=e[Eo];if(void 0!==t)return t;const n=globalThis.trustedTypes;let r=null;if(n&&"function"==typeof n.createPolicy)try{r=n.createPolicy(Ao,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){"function"!=typeof Co()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${Ao}". Allow it in the CSP (\`trusted-types ${Ao};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,e)}return e[Eo]=r,r}(),n=t?.createHTML;if("function"==typeof n)return n.call(t,e);if(!("trustedTypes"in globalThis))return e;const r=Co(),i=r?.createHTML;return"function"==typeof i?(xo||(xo=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${Ao}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${Ao};\` in the CSP to avoid this. See docs/csp.md section 7.`)),i.call(r,e)):e}const Po=new Map;let Oo=class extends HTMLElement{_uuid=co();constructor(){super()}async _loadTemplateFromSource(e){try{const t=await fetch(e);t.ok||ho(`${lo.layout} failed to fetch layout from source: ${e}, status: ${t.status}`);const n=await t.text();return Po.set(e,n),n}catch(t){ho(`${lo.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(`${lo.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(e)Po.has(e)?n.innerHTML=To(Po.get(e)||""):n.innerHTML=To(await this._loadTemplateFromSource(e)||"");else if(t){const e=this._loadTemplateFromDocument(t);e?n.innerHTML=To(e):console.warn(`${lo.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")&&ao}get name(){return this.getAttribute("name")||""}};class Lo extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||ho(`${lo.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")&&ao}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const Mo=new Set(["props","states","attr",""]);function Io(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 jo(e,t){e.hasAttribute("data-bind")||ho(`${e.tagName} has no 'data-bind' attribute.`);const n=e.getAttribute("data-bind")||"";Mo.has(n)||ho(`${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&&Io(e,t,r)}).catch(()=>{ho(`Failed to define custom element: ${i}`)}):Io(e,t,r)}const Ro=Symbol.for("wcstack.binder");function Ho(){const e=globalThis[Ro];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}const Wo=Symbol.for("wcstack.binder.pending"),zo=Symbol.for("wcstack.binder.taken");function Do(){const e=globalThis;let t=e[zo];return void 0===t&&(t=new WeakSet,e[zo]=t),t}function Uo(e,t){const n=Ho();return null===n?(function(){const e=globalThis;let t=e[Wo];return void 0===t&&(t=[],e[Wo]=t),t}().push(e),!1):(Do().add(e),n.bind(e,t),!0)}const qo={range:!0};function Fo(e,t){for(const n of e.routeChildNodes)t.add(n.placeHolder).add(n.endMarker),Fo(n,t);return t}function Bo(e){const t=e.placeHolder,n=e.endMarker,r=null!==n.parentNode&&n.parentNode===t.parentNode&&!!(4&t.compareDocumentPosition(n)),i=r?null:Fo(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 Ko=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||ho(`${lo.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(`${lo.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!==Ho())for(const t of e)1===t.nodeType&&Uo(t,qo)}(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=>{jo(t,e)}),t.hasAttribute("data-bind")&&jo(t,e))}};function Go(){return document.createElement(lo.layoutOutlet)}const Vo="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)),ho(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 ${Vo}`:`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 ${Vo}`}(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 Qo(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 Xo(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===lo.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),Qo(r,a),n.push(a),o=a.placeHolder,l=a}else{if(a===lo.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===lo.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=Go();r.layout=n,o=r,l=t}}const u=await Xo(e,l,n,r);l.replaceChildren(),l.appendChild(u),s.appendChild(o)}else s.appendChild(t);return s}async function Yo(e){const t=new Map;return await Xo(e,e.template.content,[],t)}function Zo(e){return!1!==e.checkVisibility?.()}function el(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=po[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)el(i,t,n,r)}function tl(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)el(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 nl=null,rl=null;function il(){const e=uo;return 0===e.length?null:(nl===e&&rl||(nl=e,rl=new RegExp(`\\/[^/]+(?:${e.map(e=>e.replace(/\./g,"\\.")).join("|")})$`,"i")),rl)}function sl(e){let t=e||"/";t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/");const n=il();return n&&(t=t.replace(n,"")),""===t&&(t="/"),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function ol(e,t){let n=e;return""!==t&&(e===t?n="":e.startsWith(t+"/")&&(n=e.slice(t.length))),""===n?"/":n}function ll(e){let t=e||"";if(!t)return"";t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/");const n=il();return n&&(t=t.replace(n,"")),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),"/"===t?"":t}function al(e){if(null!==e.held)return;const t=Bo(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 ul(e){e.clearParams(),al(e)}function cl(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=>{jo(t,e.typedParams)}),n.hasAttribute("data-bind")&&jo(n,e.typedParams),n.querySelectorAll(lo.layoutOutlet).forEach(t=>{t.assignParams(e.typedParams)}),n.tagName.toLowerCase()===lo.layoutOutlet&&n.assignParams(e.typedParams)}}const hl=new WeakSet;function dl(e){const t=e.placeHolder;null!==t.parentNode&&(hl.has(e)||null!==e.endMarker.parentNode?(al(e),t.after(e.held),e.held=null):t.after(...e.childNodeArray,e.endMarker),hl.add(e))}const fl=Symbol.for("wcstack.transition-runner");const pl=new WeakSet,ml="data-wcs";function gl(e,t,n){!pl.has(e)&&function(e){return e.hasAttribute(ml)||null!==e.querySelector(`[${ml}]`)}(e)&&(pl.add(e),function(e){"complete"===document.readyState?e():window.addEventListener("load",e,{once:!0})}(()=>{var r;null!==Ho()||(r=e,Do().has(r))||console.warn(`[@wcstack/router] ${t} contains ${ml} 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 yl(e){for(const t of e.childNodeArray)if(1===t.nodeType){if(t.isConnected){if(Uo(t,qo))continue}else if(null!==Ho())continue;gl(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 bl(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 fo)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 vl(e,t,n,r,i=""){const s=ol(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=tl(e,s);o||(e.fallbackRoute?o={routes:[e.fallbackRoute],params:{},typedParams:{},path:s,lastPath:r}:ho(`${lo.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 bl(e,t))return!1;const r=new Set(t.routes),i=new Set(n),s=()=>{for(const e of n)r.has(e)||ul(e);const e=[];for(const n of t.routes)(e.length>0||!i.has(n)||n.shouldChange(t.params))&&(e.push(n),cl(n,t));let s=!1;for(const t of e){const e=i.has(t);e&&s||dl(t),s||=e,n.length>0&&!e&&yl(t)}};let o;return 0===n.length?s():o=function(e,t,n){const r=function(e){const t=globalThis[fl];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 wl(){const e=window.navigation;return e?"function"!=typeof e.addEventListener||"function"!=typeof e.removeEventListener?null:e:null}function _l(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 $l(e){return"?"===e?"":e}function kl(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 Sl(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const Nl=Object.freeze({});class El 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=Nl;_typedParams=Nl;_searchParams=Nl;_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 sl(e)}_normalizeBasename(e){return ll(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(lo.outlet))return e;const t=document.createElement(lo.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||ho(`${lo.router} has no outlet.`),this._outlet}get template(){return this._template||ho(`${lo.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=mo(e.search),i=e.data??null,s=this._data!==i,o=!go(this._params,t),l=this._routeName!==e.routeName,a=!go(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(`${lo.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(`${lo.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=_l(e),r=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,i=r+$l(n.search)+n.hash,s=wl();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(ol(e,this._basename));await vl(this,this.outlet,e,this._path,$l(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(ol(n,this._basename)),i=r&&("push"===e.navigationType||"replace"===e.navigationType),s=t.search,o=this;e.intercept({handler:async()=>{try{await vl(o,o.outlet,n,o.path,s)}catch(e){throw console.error(`${lo.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 vl(this,this.outlet,e,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const e=Sl();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||ho(`${lo.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||ho(`${lo.router} should have a <template> child element.`);const r=e?this._template.content.cloneNode(!0):null,i=await Yo(this),s=!e&&this._outlet.hasAttribute(vo);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&&ho(`${lo.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(vo);const e=this._outlet.rootNode;for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(i)}await vl(this,this.outlet,o,this._path,window.location.search||""),(s||null!==Ho())&&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(lo.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(_o)){const r=t.slice(15);if(i.has(r)||!n.has(r))return!1;i.set(r,e)}else if(t.startsWith($o)){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(ko)){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=ol(e,this._basename);let h=tl(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($o)){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()===lo.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(vo);for(const e of h.routes)cl(e,h);return this.outlet.lastRoutes=h.routes,!await bl(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=ol(e,this._basename),n=tl(this,t),r=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===r.length&&ho(`${lo.router} No route matched for path: ${t}`),!r.some(e=>e.hasGuard)){await vl(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(e=>{e.placeHolder.data=`${_o}${e.absolutePath}`}),this.outlet.setAttribute(vo,"");for(const e of this.outlet.lastRoutes)e.placeHolder.after(document.createComment(`${$o}${e.absolutePath}`))}}_offerInitialContentToBinder(){for(const e of this.outlet.lastRoutes)for(const t of e.childNodeArray)t.nodeType===Node.ELEMENT_NODE&&t.isConnected&&Uo(t,qo)}_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(!kl(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),Sl()){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=wl();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&&(wl()?.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 Al=["title","rel","target","download","hreflang","lang","dir"];class Cl extends HTMLElement{static get observedAttributes(){return["to",...Al]}_childNodeArray=[];_uuid=co();_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(lo.router);if(e)return this._router=e;const t=this.getRootNode(),n=t.querySelector?.(lo.router);if(n)return this._router=n;ho(`${lo.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 sl(e)}_joinInternalPath(e,t){const n=ll(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}=_l(t),s=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);e.href=s+$l(r)+i}else try{e.href=new URL(t).toString()}catch{ho(`[${lo.link}] Invalid URL in 'to' attribute: ${t}`)}}connectedCallback(){Sl()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const e=this.nextElementSibling;return null!==e&&"A"===e.tagName&&e.hasAttribute(wo)?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(wo),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-")||Al.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,Sl())return this._updateActiveState(),void n.setAttribute(wo,"");wl()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!wl()?.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(){wl()?.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(Al.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}=_l(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 xl=[],Tl=new Map;let Pl=!1;const Ol=new WeakMap;class Ll 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(),Pl||(this._captureInitialHead(),Pl=!0),xl.push(this),this._reapplyHead()}disconnectedCallback(){const e=xl.indexOf(this);-1!==e&&xl.splice(e,1),this._reapplyHead()}get childElementArray(){return this._initialized||ho("Head component is not initialized yet."),this._childElementArray}_getKey(e){const t=Ol.get(e);if(void 0!==t)return t;const n=this._computeKey(e);return Ol.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);Tl.has(e)||Tl.set(e,t.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of xl)for(const n of t._childElementArray)e.add(this._getKey(n));for(const t of Tl.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=xl.length-1;t>=0;t--){const r=xl[t];for(const t of r._childElementArray)if(this._getKey(t)===n){e=t.cloneNode(!0);break}if(e)break}!e&&Tl.has(n)&&(e=Tl.get(n).cloneNode(!0));const r=t.get(n)??null;e?(r?r.replaceWith(e):document.head.appendChild(e),t.set(n,e),Uo(e)||gl(e,`<${e.tagName.toLowerCase()}> inside <${lo.head}>`,`<${lo.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(lo.layout)||e.define(lo.layout,Oo),e.get(lo.layoutOutlet)||e.define(lo.layoutOutlet,Ko),e.get(lo.outlet)||e.define(lo.outlet,Lo),e.get(lo.route)||e.define(lo.route,So),e.get(lo.router)||e.define(lo.router,El),e.get(lo.link)||e.define(lo.link,Cl),e.get(lo.head)||e.define(lo.head,Ll)}(void 0);const Ml="data-fetchtarget",Il={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let jl=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 Rl(e,t){return t.every(t=>"available"===e.availability.get(t))}const Hl=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let Wl=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 jl("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 Rl(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}}(Hl,{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(!Rl(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)}}},zl=!1;function Dl(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest(`[${Ml}]`);if(!n)return;const r=n.getAttribute(Ml);if(!r)return;const i=customElements.get(Il.fetch),s=document.getElementById(r);if(!(i&&s instanceof i))return;const o=s;o.url&&(e.preventDefault(),o.fetch())}function Ul(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 ql=Symbol.for("wcstack.trustedTypes.policy");function Fl(){const e=globalThis[ql];return null===e||"object"!=typeof e?null:e}let Bl,Kl=!1;let Gl=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Wl.wcBindable,properties:[...Wl.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 Wl(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(Il.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(Il.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=Fl(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(t)}catch(e){if(function(){if(void 0!==Bl)return Bl;if(!("trustedTypes"in globalThis))return Bl=!1,Bl;try{document.createElement("div").innerHTML="<i></i>",Bl=!1}catch{Bl=!0}return Bl}())return void function(){if(Kl)return;Kl=!0;const e="function"==typeof Fl()?.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(!Ul(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this.style.display="none",zl||(zl=!0,document.addEventListener("click",Dl)),!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 Vl 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 Ql=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 Gl&&(e.loading||(e.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(e=customElements){e.get(Il.fetch)||e.define(Il.fetch,Gl),e.get(Il.fetchHeader)||e.define(Il.fetchHeader,Vl),e.get(Il.fetchBody)||e.define(Il.fetchBody,Jl),e.get(Il.infiniteScroll)||e.define(Il.infiniteScroll,Ql)}(void 0);const Xl="data-storagetarget",Yl={storage:"wcs-storage"},Zl="wcs-storage:value-changed",ea="wcs-storage:loading-changed",ta="wcs-storage:error",na="wcs-storage:error-info-changed",ra="wcs-storage:trigger-changed";let ia=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:Zl,semantics:"state",getter:e=>e.detail},{name:"loading",event:ea,semantics:"state"},{name:"error",event:ta,semantics:"state"},{name:"errorInfo",event:na,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(ea,{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(ta,{detail:e,bubbles:!0})))}_commitErrorInfo(e){this._errorInfo=e,this._target.dispatchEvent(new CustomEvent(na,{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)}},sa=!1;function oa(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest(`[${Xl}]`);if(!n)return;const r=n.getAttribute(Xl);if(!r)return;const i=customElements.get(Yl.storage),s=document.getElementById(r);i&&s instanceof i&&(e.preventDefault(),s.save())}function la(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 aa=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...ia.wcBindable,properties:[...ia.wcBindable.properties,{name:"trigger",event:ra,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 ia(this),this._internals=this._initInternals(),this._wireStates({[ea]:e=>({loading:!0===e}),[ta]: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(ra,{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(!la(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this.style.display="none",sa||(sa=!0,document.addEventListener("click",oa)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(e=customElements){e.get(Yl.storage)||e.define(Yl.storage,aa)}(void 0);const ua="*",ca="vanilla",ha={loaders:{[ca]:{postfix:".js",loader:async function(e){return(await(import(`${e}`))).default}},[ua]:ca},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function da(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 fa(e,t,n){let r;if(null===t||t===ua||""===t){let t=null;const i=[];for(const[e,t]of Object.entries(n)){if(e===ua)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[ua],"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 pa=new Set,ma=new Map;let ga=new WeakMap;function ya(e){if(e===globalThis.customElements)return ma;let t=ga.get(e);return void 0===t&&(t=new Map,ga.set(e,t)),t}const ba=new Map;async function va(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 ba)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){pa.has(t)||(console.error(`Failed to eager load component '${t}':`,e),pa.add(t))}}function wa(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 _a(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&&ba.set(e,t)});const $a=new WeakSet,ka=new WeakSet;async function Sa(e,t,n){e.shadowRoot&&($a.has(e)||await async function(e,t,n){$a.add(e),await Ca(e.shadowRoot,t,n)}(e,t,n))}async function Na(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=ya(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=fa("",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),pa.add(e.name)}}(e,t,i,r);s.set(e.name,l);try{await l}finally{s.delete(e.name)}}async function Ea(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=_a(e);void 0===r.get(i.name)?(ka.has(e)||(ka.add(e),r.whenDefined(i.name).then(async()=>{await Sa(e,t,n)})),l.has(i.name)||pa.has(i.name)||(l.add(i.name),o.push(i))):await Sa(e,t,n)}let a=0;for(const e of o)await Na(e,t,n,r),a++;return a}async function Aa(e,t,n,r){for(;await Ea(e,t,n,r)>0;);}async function Ca(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 wa(t)}return wa(globalThis.customElements)}(e);if(null===r)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await Aa(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 Aa(e,t,n,r)}catch(e){console.error("Failed to lazy load components: "+e)}});return i.observe(e,{childList:!0,subtree:!0}),i}class xa extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),xa._instance)throw new Error(`${ha.tagNames.autoloader} can only be instantiated once.`);xa._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=da(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=fa(i.key,i.loaderKey,t)}catch(e){throw new Error("Loader redirection is not supported for eager loaded components: "+r)}n.push(va(i,r,s))}await Promise.all(n)}(n,ha.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 Ca(document,ha,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,xa._instance===this&&(xa._instance=null)}}!function(e=customElements){e.get(ha.tagNames.autoloader)||e.define(ha.tagNames.autoloader,xa)}(void 0);
|
|
1
|
+
var e=class{constructor(e,n,r){this.c=[],this.getter=null,this.ie=null,this.se=!1,this.M=[],this.Q=[],this.ft=null,this.A=-1,this.z=t,this.Ce=null,this.Ot=null,this.Ct=null,this._=null,this.pn=!1,this.mn=!1,this._n=!1,this.Z=0,this.pt=new Set,this.t=e,this.d=r,this.s=n;let i=null===r?[null]:r.h.slice(),s="*"===n;s&&i.push(r),this.n=i.length-1,this.K=s?[]:null===r?[n]:[...r.K,n],this.h=i}Wn(e){this.pt.has(e)||(this.pt.add(e),this.M.push(e),e.Q.push(this))}Io(e){this.pt.delete(e);let t=this.M;t.splice(t.indexOf(e),1)}jo(){this.getter=null,this.ie=null,this.A=-1,this.z=t,this.M.length=0,this.pt.clear(),this.Q.length=0,this.ft=null,this.Ce=null,this.Ot=null,this.Ct=null,this._=null}ee(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.mt=new Map,this.Vn=e}It(e){return this.mt.get(e)}get(t){let n=this.mt.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.Vn?.(n),this.mt.set(t,n),i&&i.c.push(n),n}all(){return this.mt.values()}jt(e){this.mt.delete(e.t)}},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.size>4095&&s.clear(),s.set(e,o),o}var l=class{constructor(e,t,n){this.ht=null,this.$=null,this.he=null,this._=null,this.c=null,this.y=!0,this.l=e,this.b=t,this.R=n}},a=class{constructor(e,t){this.C=null,this.f=[],this.$=null,this.B=null,this.te=!1,this.Lt=!1,this.yt=!1,this.o=e,this.ae=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.Dt&&Array.isArray(t)){let e=t.filter(e=>!g.has(e));if(e.length>0)return c.Dt(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.Bo?.(e,t,n)??""}`)}function w(e,t=[]){return c.Do?.(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.wt=new Set,this.name=e}get size(){return this.wt.size}subscribe(e){return this.wt.add(e),()=>{this.wt.delete(e)}}unsubscribe(e){return this.wt.delete(e)}emit(...e){let t=[];for(let n of this.wt)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 A(e,t,n){let r=N(e);if(null!==r)return r.run(t,{source:e,types:n});t()}var E="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?{Hn:s,args:[],literals:[]}:{Hn: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),{Qe:r,Ze:n}}var z=[["$watch","temporal"],["$stream","temporal"],["$listKeys","list-keys"],["$recursion","recursion"]],D=["enableMustache","sameValueGuard","enableDirectionalInitialSync"];function F(e){return e.includes("**")&&H(e),e}var U=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,G=()=>[];function K(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._?.get(t);void 0!==r&&r.delete(n)&&0===r.size&&e._.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.ae;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.h[n]?r:null}var Z=class{constructor(e,t){this.Ie=0,this.u=null,this.je=0,this.bt=new Set,this.et=new Map,this.Un=Symbol("wcs.block"),this.element=null,this.vt=[],this.Le=null,this.qn=[],this.Vt=0,this.X=null,this.oe=new Map,this.ce=new Map,this.Be=[],this.De=[],this.Me=[],this.kt=!1,this.hn=!1,this.Ht=new WeakMap,this.W=0,this.Ut=0,this.gn=!1,this.qt=!1,this.Kt=!1,this.Pe=0,this.Kn=()=>{this.W=0,this.gn=!1},this.zn=()=>{this.Pe--},this.rp=null,this.rr=null,this.Mo=()=>this.zt(),this._o=(e,t)=>e(this.proxy,...t),this.Xn=[],this.tt=[],this.Wo={$untracked:e=>{let t=this.X;if(null===t)return e();t.ye++;try{return e()}finally{t.ye--}},$eqIndex:(e,t=1)=>{let n=X(this.u,t);null===n&&_(7,[e]);let r=this.o(e);if(null!==r.getter||r.se)return this.watchIndex(t),n.b===this.read(r,null);let i=this.X;if(null!==i){let e=i.getter,n=r.Ce??(r.Ce=[]);if(!n.some(n=>n.getter===e&&n.Yn===t)){n.push({getter:e,Yn:t});let i=e.h[t];(i.Ot??(i.Ot=[])).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.u,n.n)))},$dependOn:e=>{this.resolve(F(e),this.u),null!==this.X&&0===this.X.ye&&this.Gn(this.rp,this.rr,this.X)},$getAll:(e,t)=>this.getAll(e,t),$setAll:(e,t,n,r)=>this.yn(e,t,n,r),$resolve:(...e)=>{let t=F(e[0]),n=e[1]??[],r=this.o(t,!0);this.wn("$resolve",t,r,n,!0);let i=this.Jn(r,n,null);if(e.length<3)return this.read(r,i);this.T(r,i,e[2])},$postUpdate:e=>{this.resolve(F(e),this.u);let t=this.rp,n=this.rr;"*"===t.s&&null!==n&&(n.R=n.l.C[n.b],this.P.Xt(n)),this.bn(t,n),null!==n&&this.Qn(n,t,void 0,n.R,!1),0===t.n&&this.Zn(t,void 0,void 0,!0),this.Yt(t,n,void 0,void 0,!1)}},this.P=t,this.I=new i(e=>{this.tt.push(e),this.nt(e)}),this.eo(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.ot(t);if(t.indexOf(".")<0){let e=n.I.It(t);if(void 0===e||null===e.getter){let e=i[t];if("function"==typeof e)return r===n.proxy&&n.V?.(e)||e}if(void 0!==e&&0===e.n)return n.read(e,null)}return n.resolve(t,n.u),n.read(n.rp,n.rr)},set:(e,t,r)=>"symbol"==typeof t?Reflect.set(n.target,t,r):(n.resolve(F(t),n.u),n.T(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,t){let n=this.I.get(e);return t||(n.pn=!0),n}to(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.ie=r.set??null,null!==i.getter&&i.n>0&&(i.A=this.Ie++)}for(let e of this.I.all())this.nt(e)}nt(e){e.t.includes("**")&&H(e.t),("__proto__"===e.s||"prototype"===e.s)&&_(120,[e.t]);let t=e.d;e.se=null!==t&&"*"!==e.s&&t.n===e.n&&(null!==t.getter||t.se),null===e.getter&&this.Vo(e)}Vo(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.u),this.rp!==e?this.read(this.rp,this.rr):this.read(e.d,this.u)?.[n]),e.ie=r=>{if(this.resolve(t,this.u),this.rp!==e)return this.T(this.rp,this.rr,r);let i=this.read(e.d,this.u);null==i&&_(4,[t,i]),i[n]=r}}e._n=!0,e.n>0&&(e.A=this.Ie++)}_e(e,t){let n=null===e?this.oe:e.c??=new Map,r=n.get(t);return void 0===r&&n.set(t,r=new a(t,e)),t.pn=!0,this.Y(r),r}no(e){try{this.Y(e)}catch(t){this.Gt(t,e.o.t,e.$?.S??null,"for")}}Y(e){let t=this.v(e.o,e.ae);if(t===e.C)return;this.oo(e);let n=function(e,t,n){let r=Array.isArray(t)?t:u;if(r===e.C)return null;let i=e.f,s=r.length,o=i.length,a=new Array(s),c=0;for(;c<s&&c<o&&i[c].R===r[c];)a[c]=i[c],c++;let h=o-1,d=s-1;for(;h>=c&&d>=c&&i[h].R===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.Bt(i[e]);else{let t=h<d?h:d;for(let e=c;e<=t;e++)i[e].R===r[e]&&(a[e]=i[e]);let s=new Map;for(let e=h;e>=c;e--){let n=i[e];if(e<=t&&a[e]===n)continue;let r=s.get(n.R);void 0===r?s.set(n.R,n):Array.isArray(r)?r.push(n):s.set(n.R,[r,n])}for(let t=c;t<=d;t++){if(void 0!==a[t])continue;let n,i=r[t],o=s.get(i);void 0!==o&&(Array.isArray(o)?(n=o.pop(),0===o.length&&s.delete(i)):(n=o,s.delete(i))),a[t]=n??new l(e,t,i)}for(let e of s.values())if(Array.isArray(e))for(let t of e)n.Bt(t);else n.Bt(e)}for(let e=c;e<s;e++){let t=a[e];t.b!==e&&(t.b=e,n.Lo(t))}return e.f=a,e.C=r,i}(e,t,this);if(null===n)return;if(e.C===t){let n=q(this.Ht,t,G);if(n.push(e),n.length>1)for(let e of n)e.yt=!0}c.Jt?.(this,e,n),(null!==e.$||null!==e.B)&&!e.te&&(e.te=!0,this.De.push(e),this.Te());let r=e.o.Ot;if(null!==r)for(let{source:t,getter:i}of r){let r=this.v(t,null),s=n[r],o=e.f[r];s!==o&&(void 0!==s&&s.y&&this.vn(i,s),void 0!==o&&this.vn(i,o))}}Lo(e){this.P.Ho(this,e)}Bt(e){e.y=!1;let t=e._;if(null!==t){for(let e of t)J(e.source,e.key,e.sub);e._=null}if(null!==e.c)for(let t of e.c.values()){this.oo(t);for(let e of t.f)this.Bt(e)}}oo(e){let t=this.Ht.get(e.C);void 0!==t&&(t.splice(t.indexOf(e)>>>0,1),e.yt=!1,1===t.length&&(t[0].yt=!1))}resolve(e,t){let n=o(e),r=this.rp=this.o(n.o,!0),i=n.indexes;this.rr=0===r.n?null:null===i?Y(t,r,r.n):this.Jn(r,i,t,e)}Jn(e,t,n,r){let i=null;for(let s,o=1,l=0;o<=e.n;o++){let a=e.h[o],c=this._e(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("."),!0),o--;continue}if(i=c.f[h]??null,null===i)break}return this.rp=e,i}rt(e,t){return 0===e.n?Q(this.target,e.K):null===t?void 0:Q(t.R,e.K)}read(e,t){let n=this.X;if(null!==n&&0===n.ye&&this.Gn(e,t,n),null!==e.getter)return this.P.Uo(this,e,t);if(e.se){let n=this.read(e.d,t);return n?.[e.s]}return null===e.d&&!(e.s in this.target)&&!this.bt.has(e.s)&&"then"!==e.s&&"toJSON"!==e.s&&_(301,[e.t],e.s,Object.keys(this.target)),this.rt(e,t)}v(e,t){let n=this.X;if(null===n)return this.read(e,t);n.ye++;try{return this.read(e,t)}finally{n.ye--}}Gn(e,t,n){let r=n.getter;e.Wn(r),0===r.n?e.Z!==n.ue&&(e.Z=n.ue,n.kn.push(e)):e.n>0&&X(t,Math.min(e.n,r.n))!==X(n.r,Math.min(e.n,r.n))&&(r.ft??(r.ft=new Set)).add(e)}qo(e,t){for(let n=0;n<this.Vt;n++){let r=this.qn[n];r.getter===e&&r.r===t&&_(701,[e.t])}this.Vt>=128&&_(801,[e.t]);let n=this.Vt++;this.je++;let r=this.qn[n]??={getter:e,r:t,ye:0,ue:0,kn:[]};r.getter=e,r.r=t,r.ye=0,r.ue=++U,r.kn.length=0;let i=this.X;this.X=r;let s=this.u;this.u=t;try{let t=e.getter.call(this.proxy);return 0===e.n&&this.Ko(e,r),t}finally{this.je--,this.Vt--,this.X=i,this.u=s,r.r=null}}Ko(e,t){let n=t.ue;for(let e of t.kn)e.Z=n;e.Q=e.Q.filter(t=>t.Z===n||t.n>0||!t.se&&Array.isArray(null!==t.getter?t.z:this.rt(t,null))||this.io(t,e))}io(e,t){return e.Io(t),this.tt.push(e),!1}zo(){for(let e=this.tt;e.length>0;e=this.tt){this.tt=[];let t=new Set;for(let n of e)if(!(n.pn||n.mn||null===n.d||n.c.length>0||n.M.length>0)&&(null===n.getter||n._n&&n.A<0)&&null===n._){n.mn=!0,this.I.jt(n),t.add(n.d);for(let e of n.Q)this.io(e,n)}for(let e of t)(e.c=e.c.filter(e=>!e.mn)).length||this.tt.push(e)}}watchIndex(e){let t=this.X;if(null!==t&&0===t.ye){let n=t.getter,r=n.h[e];if(r){let e=r.Ct??(r.Ct=[]);e.includes(n)||e.push(n)}}}ot(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.u,n)?.b}let n=this.Wo[e];if(void 0!==n)return n;switch(e){case"$stateElement":return this.element;case"$command":return this.commands}return c.ot?.(this,e)}eq(e,t){this.resolve(e,this.u);let n=this.rp,r=this.rr;if(null!==n.getter||n.se||n.n>0)return V(this.read(n,r),t);let i=this.X;return null!==i&&0===i.ye&&this.Xo(n,t,i),V(this.v(n,null),t)}Xo(e,t,n){let r=n.getter,i=n.r,s=null===i?this.Xn:i._??(i._=[]);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.ue=n.ue);o.ue!==n.ue&&(J(e,o.key,o.sub),s.splice(i--,1))}}let o={getter:r,r:i};q(e._??=new Map,t,B).add(o),s.push({source:e,key:t,sub:o,ue:n.ue})}Zn(e,t,n,r){this.Qt(e,i=>{let s=i._;if(null===s&&null===i.Ce)return;let o=i===e?[]:i.t.slice(e.t.length+1).split("."),l=Q(t,o),a=Q(n,o);if(null!==i.Ce&&this.Yo(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.P.we(this,n.getter,n.r):J(i,e,n)}})}T(e,t,n,r=!1,i=!1){if(this.je>0&&_(8),i||this.Pe>0?this.qt=!0:this.Kt=!0,c.Ae?.(this,e,t,n,i))return;if(null!==e.ie){try{this.Sn(e.ie,t,[n])}finally{this.Yt(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.se?this.v(e,t):this.rt(e,t);if(r||!this._t||!Object.is(s,n)||Object(n)===n){if("*"===e.s){let e=t;e.l.C[e.b]=n,e.R=n,this.P.Xt(e)}else{let r=1===e.K.length?0===e.n?this.target:t.R:this.v(e.d,t);null==r&&_(4,[e.t,r]),r[e.s]=n}this.En(e,t),null!==t&&this.Qn(t,e,s,n),0===e.n&&this.Zn(e,s,n),this.Yt(e,t,s,n,!0)}}so(e){return(this.Ht.get(e.C)??[]).filter(t=>t.C===e.C&&(null===t.ae||t.ae.y))}Qn(e,t,r,i,s=!0){let o=e.l;if(!o.yt&&null===o.o.getter&&!o.o.M.length)return;let l=e.R,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}`,!0);""===a&&(n.R=i,this.P.Xt(n)),s?this.En(o,n):this.bn(o,n),this.Yt(o,n,r,i,s)};for(let t of this.so(o))u(t,t.f[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.Ht.get(e)??[])for(let e of t.f)e.R===l&&u(t,e);for(let r of t){let t=r.z,i=t===n;i&&(t=this.oe.get(r)?.C),(i||h(t))&&!c.has(r.M)&&c.add(r.M)&&(!i&&t!==e&&this.P.we(this,r,null),d(t,r.M))}},f=e=>{for(let t of e.Q)if(!c.has(t)&&c.add(t))if(null!==t.getter)f(t);else if(!t.se){let e=this.rt(t,null);h(e)&&d(e,t.M)}};null!==o.o.getter?f(o.o):d(o.C,o.o.M)}bn(e,t){this.Go(e,t,e=>{this.Y(e);for(let t of e.yt?this.so(e):[e]){let e=this.o(`${t.o.t}.*`);for(let n of t.f)this.St(e,n),this.bn(e,n)}})}En(e,t){let n=null===t?this.oe:t.c;if(null!==n)for(let t of n.values())t.o.ee(e)&&this.Y(t)}Go(e,t,n){let r=null===t?this.oe:t.c;if(null!==r)for(let t of r.values())t.o.ee(e)&&n(t)}Yo(e,t,n,r){for(let{getter:i,Yn:s}of e.Ce)this.lo(i.h[s],e=>{for(let s of r?e.f.keys():[t,n]){let t="number"==typeof s?e.f[s]:void 0;void 0!==t&&this.vn(i,t)}})}vn(e,t){t.l.n===e.n?this.P.we(this,e,t):this.Zt(t,e,t=>this.P.we(this,e,t))}Yt(e,t,n,r,i){c.be?.(this,e,t,n,r,i),this.We(e,t)}We(e,t){this.P.Jo(this,e,t),this.Te()}ao(e){let t=this.et.get(e);if(void 0!==t)return t;let n=Symbol(`wcs.on${e}`);this.et.set(e,n);let r=this.root,i=this.Un;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.Qo(e,t))return}}),n}reset(e){let t=this.target,n=this.bt;for(let e of this.I.all())null===e.d&&null!==e.getter&&n.add(e.s);this.eo(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.ce.values())for(let t of e)this.en(t);for(let e of this.oe.values())this.co(e);this.Le=null;try{this.zt()}finally{this.$n()}c.element?.(this,"reset")}eo(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.Mt||i!==this._t||s!==this.Wt)&&_(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._o);this.Mt=r,this._t=i,this.Wt=s,c.de?.(this,e),this.target=e,this.Ie=0;for(let e of this.I.all())e.jo();this.Xn.length=0,this.to(e),this.commands=o,this.Re=l}co(e){this.no(e);let t=this.o(`${e.o.t}.*`);for(let n of e.f)if(n.ht=null,n._=null,this.St(t,n),null!==n.c)for(let e of n.c.values())this.co(e)}H(e){let t=[];for(let n=e;null!==n;n=n.l.ae)t.unshift(n.b);return t}Zo(e,t,n){let r=this.Re.get(e);void 0===r&&_(1301,[e],e,this.Re.keys()),r.emit(t,...this.H(n))}command(e){let t=this.commands[e];return void 0===t&&_(1302,[e],e,Object.keys(this.commands)),t}er(e,t,n){this.command(e).emit(t,...this.H(n))}tr(e,t,n){let r=e.includes(".")?this.v(this.o(e),null):this.target[e];return"function"!=typeof r&&_(5,[e]),this.Sn(r,n,[t,...this.H(n)])}Sn(e,t,n){let r=this.u;this.u=t;try{return e.apply(this.proxy,n)}finally{this.u=r}}St(e,t){if(null!==e.getter){let n=null===t?this.oe:t.c;if(null!==n)for(let t of n.values())!t.Lt&&t.o.ee(e)&&(t.Lt=!0,this.Me.push(t))}if(null===t)return void this.Qt(e,e=>{let t=this.ce.get(e);if(void 0!==t)for(let e of t)this.en(e)});let n=t.he;if(null!==n)for(let t=0;t<n.length;t++)n[t].o.ee(e)&&this.en(n[t]);let r=t.$;null!==r&&null!==r.fe&&r.uo(this,e);let i=t.l.B;if(null!==i)for(let n of i){let r=n.map.get(t);void 0!==r&&null!==r.fe&&r.uo(this,e)}}Nn(e,t,n){this.Qt(e,e=>{let r=e.M;for(let i=0;i<r.length;i++){let s=r[i];if(0===s.n)this.it(s,null,n);else if(null===t||0===e.n||s.h[1]!==e.h[1]||null!==s.ft&&s.ft.has(e))this.tn(s.h[s.n],e=>this.it(s,e,n));else if(s.n<=e.n){let e=X(t,s.n);null!==e&&this.it(s,e,n)}else this.Zt(t,s,e=>this.it(s,e,n))}})}it(e,t,n){n(e,t)&&(c.ve?.(this,e,t),this.St(e,t),this.Nn(e,t,n))}Qt(e,t){t(e);let n=e.c;for(let e=0;e<n.length;e++)this.Qt(n[e],t)}tn(e,t){this.lo(e,e=>{for(let n of e.f)t(n)})}lo(e,t){if(0===e.n){let n=this.oe.get(e);return void(void 0!==n&&t(n))}this.tn(e.h[e.n],n=>{let r=n.c?.get(e);void 0!==r&&t(r)})}Zt(e,t,n){if(e.l.n===t.n)return n(e);let r=e.c?.get(t.h[e.l.n+1]);if(void 0!==r)for(let e of r.f)this.Zt(e,t,n)}nr(e){let t=e.r;null===t?q(this.ce,e.o,B).add(e):(t.he??(t.he=[])).push(e)}xn(e){let t=e.r;if(null===t)return void this.ce.get(e.o)?.delete(e);let n=t.he;t.y&&null!==n&&n.splice(n.indexOf(e)>>>0,1)}en(e){e.te||(e.te=!0,this.Be.push(e),this.Te())}Te(){this.kt||(this.kt=!0,queueMicrotask(this.Mo))}Rn(){for(let e of this.Be)e.te=!1;for(let e of this.De)e.te=!1;for(let e of this.Me)e.Lt=!1;this.Be=[],this.De=[],this.Me=[],this.P.bt(this)}fo(e,t){let n=[...new Set([...this.Be,...this.De,...this.Me].map(e=>e.o.t))];console.error(`[@wcstack/state] ${w(e)}`,n),c.st?.(this,{type:"state:render-chain-limit",maxDepth:t,paths:n}),this.Rn()}zt(){this.kt=!1;let e=this.Ut;this.Ut=0;let t=0;if(!this.qt||this.Kt?this.Kn():e>0?t=e:1===(t=++this.W)&&setTimeout(this.Kn,0),this.qt=this.Kt=!1,t>100)101===t?this.fo(41,100):this.Rn();else{this.hn=!0;try{for(let e=0;this.Be.length>0||this.De.length>0||this.Me.length>0;e++){if(e>=32){this.gn?this.Rn():this.fo(11,32),this.gn=!0;break}let n=this.Me;if(n.length>0){this.Me=[];for(let e of n)e.Lt=!1,this.no(e)}let r=this.De,i=this.Be;this.De=[],this.Be=[];let s=A("state",()=>{for(let e of r){e.te=!1;for(let t of[e.$,...e.B??[]])if(null!==t&&t.y)try{t.Et()}catch(n){this.Gt(n,e.o.t,t.S,"for")}}for(let e=0;e<i.length;e++){let t=i[e];t.te&&(t.te=!1,(null===t.Pn||t.Pn.y)&&this.Ve(t))}this.hn||(this.He(),this.kt&&(this.Ut=t+1))});void 0!==s&&s.then(void 0,e=>console.error(e))}}finally{this.hn=!1}this.qt=this.Kt=!1,this.He(),c.Fe?.(this),this.zo(),e>0&&this.kt&&(this.Ut=t+1)}}$t(e,t){this.vt.push([e,t])}Gt(e,t,n,r){this.$t(e,{o:{t:t},a:n,nn:()=>r})}Ve(e){try{e.apply()}catch(t){return void this.vt.push([t,e])}null!==this.Le&&this.po(e.o,e.r)}po(e,t){let n=q(this.Le,e.t,G);null!==t&&n.push(this.H(t))}$n(){this.Le="function"==typeof this.target.$renderedCallback?new Map:null}He(){let e=this.Le;if(null!==e&&e.size>0){this.Le=new Map;let t,n=[...e.keys()],r={};for(let[t,n]of e)n.length>0&&(r[t]=n);this.Pe++;try{t=this.ke("$renderedCallback",[n,r])}catch(e){console.error(e)}K(t)?t.then(this.zn,e=>{this.zn(),console.error(e)}):this.Pe--}if(0===this.vt.length)return;let t=this.vt;this.vt=[];let n=this.target.$errorCallback;for(let[r,i]of t){c.Ue?.(this,r,i);let t=i.o.t,s=i.nn();if("function"==typeof n)try{let e=this.ke("$errorCallback",[r,{path:t,bindingType:s,node:i.a}]);K(e)&&e.then(void 0,e=>console.error(e))}catch(e){console.error(e)}else console.error(`[@wcstack/state] ${w(12,[s,t])}`,r)}}ke(e,t=[]){let n=this.target[e];return"function"==typeof n?this.Sn(n,null,t):void 0}mo(e,t,n){if(0===e.n)return void n(null,[]);let r=[],i=(s,o)=>{let l=e.h[s];this.read(l,o);let a=this._e(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.f[t[s-1]]]:a.f)void 0!==e&&u(e)};i(1,null)}getAll(e,t){let n=this.o(e,!0);void 0!==t&&this.wn("$getAll",e,n,t,!1);let r=t;if(void 0===r){r=[];let t=this.u;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.mo(n,r,e=>i.push(this.read(n,e))),i}yn(e,t,n,r){Array.isArray(t)||_(9,[e]),this.je>0&&_(8);let i=this.o(e,!0);this.wn("$setAll",e,i,t,!1);let s=[];this.mo(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.T(i,t,a),l++)}return l}wn(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([E,"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===E?(r.length>0&&_(103,[e]),t={Qe:"#else",Ze:[]}):"..."===i?(0===r.length&&_(104,[e]),t=W(r),t.Ze.length>0&&_(105,[e])):(t=W(r),"for"===i&&t.Ze.length>0&&_(121,[e])),{Se:i,Ee:[i],on:[],j:[],...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]),{Se:i,Ee:o,on:s?s.split(",").map(O):[],j:n}}(n),[l]=o.Ee;if(""===l&&o.Ee.length>1){let e=o.Ee.slice(1);return(e.includes("")||ie.has(e[0]))&&_(106,[n]),{...o,Se:e.join("."),Ee: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.Hn,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 Ae(e){return"innerHTML"===e||"outerHTML"===e||"srcdoc"===e}function Ee(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,ho:"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.Nt??=[]).push(()=>{r=null}),e.then(()=>r?.())}(l.whenDefined(o),r,()=>{try{a()}catch(r){We(e,r,t,n)}e.Te()})}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.Wt;h&&null===a&&void 0===u&&_(38,[r]);let d=t.U;(null===a?"element"===d||"auto"===d:void 0===u&&("state"===d||"auto"===d))&&_(39,[d,r]),"connect"===t.Y&&null===a&&_(40,[r]);let f=h&&null!==a&&void 0===u,p=new Fe(e,Re,n,r,i,s,o,t.N,void 0);p.j=t.j,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.ho||c.detail?.(n,r,i)),(!p.Tn||!Object.is(i,p.value))&&(i=$e(p.j,i),null===p.N&&(p.value=i),e.T(p.o,p.r,i,a.ho,!0))});let m=d??(f?"element":"state");if("state"===m)f||e.Ve(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.Ve(p));let t=n[r];null===p.N&&(p.value=t),e.T(p.o,p.r,t,!1,!0)};"connect"!==t.Y||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.Gt(t,n.o?.t??n.xt,r,He[n.i]),ze=Symbol();function De(e,t,n){let r=t.U;return null===r||"state"===r||"auto"===r&&void 0!==e.v(t.o,n)?t.q:ze}var Fe=class{constructor(e,t,n,r,i,s,o,l,a,u=null){this.te=!1,this.j=null,this.attribute=null,this.Tn=!1,this.engine=e,this.i=t,this.a=n,this.name=r,this.o=i,this.r=s,this.Pn=o,this.N=l,this.value=a,this.W=u}nn(){return He[this.i]}apply(){if(null!==this.W)return void this.W.Et();let e=$e(this.N,this.engine.read(this.o,this.r));if(e===this.value&&9!==this.i&&("object"!=typeof e||null===e||this.i===Re||8===this.i||Ae(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.rn()===e:10===this.i?t.checked=Array.isArray(e)&&e.includes(this.rn()):qe(this.i,t,this.name,e),this.value=e;else{if(void 0===e)return void(this.value=e);this.value=e,this.Tn=!0;try{t[this.name]!==e&&(t[this.name]=e)}finally{this.Tn=!1}null!==this.attribute&&function(e,t,n){try{if(null==n||!1===n)e.removeAttribute(t);else if(!0===n)e.setAttribute(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)}}rn(){return $e(this.j,this.a.value)}ir(){let e,t=this.a,n=this.engine;if(9===this.i){if(!t.checked)return;e=this.rn()}else if(10===this.i){let r=this.rn(),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.j,t[this.name]),this.value=NaN;n.T(this.o,this.r,e,!1,!0)}},Ue=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(Ue(n)?t[n]="innerHTML"===n?Ee(r):null==r?"":String(r):Ae(n)?null==r&&"srcdoc"===n?t.removeAttribute(n):void 0!==r&&(t[n]=Ee(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=Ee(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(n.includes("-")?null==r?t.style.removeProperty(n):t.style.setProperty(n,String(r)):t.style[n]=null==r?"":String(r))}}var Be=Symbol();function Ge(e){let t="optgroup"===e.localName?e.parentNode:e,n=t?.[Be];void 0!==n&&(t[n[0]]=n[1])}var Ke=class{constructor(e,t,n,r){this.y=!0,this.he=null,this.c=null,this.Nt=null,this.Fn=null,this.r=e,this.qe=t,this.L=n,this.F=r}Qo(e,t){let n=t.target,r=this.F,i=[],s=null;for(let t of r.Re){if(t.name!==e)continue;let o=r.On[t.a],l=st(null===this.L?this.qe:this.L[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.An(t,this.r);if(t.cancelBubble)return!0}return!1}get s(){return null===this.L?this.qe:this.L[this.L.length-1]}Ke(){let e=this.Fn;return(null===e?null:e.Cn(this.qe))??this.qe}insertBefore(e,t){let n=this.s;for(let r=this.Ke();;){let i=r.nextSibling;if(e.insertBefore(r,t),r===n)return;r=i}}wo(){null===this.L?this.qe.remove():ot(this.Ke(),this.s)}Ne(e){if(this.y=!1,null!==this.Nt)for(let e of this.Nt)e();let t=this.he;if(null!==t)for(let n=0;n<t.length;n++)e.xn(t[n]);if(null!==this.c)for(let e of this.c)e.Ne()}},Ve=class extends Ke{constructor(e,t,n,r){super(e,t,n,r),this.bo=0,this.V=null,this.fe=0===r.ze.length?null:new Array(2*r.ze.length)}vo(e,t){let n=this.V??=new Array(this.F.ze.length),r=n[t];if(void 0===r){let i=this.F.ze[t],s=this.fe;r=n[t]=new Fe(e,i.i,s[2*t],i.name,i.o,this.r,this,i.N,s[2*t+1])}return r}uo(e,t){let n=this.F.ze;for(let r=0;r<n.length;r++)n[r].o.ee(t)&&e.en(this.vo(e,r))}Ne(e){let t=this.r;t.$===this&&(t.$=null),super.Ne(e)}};function Je(e,t,n,r){let i=X(n,t.n);try{return e._e(i,t)}catch(n){return e.Gt(n,t.t,r,"for"),null===i?e.oe.get(t):i.c.get(t)}}function Qe(e,t,n){n&&e.nr(t);let r=t.Pn;null!==r&&(r.he??=[]).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.On,l=t.build,a=t.ko,u=null,h=c.Oe?.(t,null===r?i:r.S,null!==r),d=!h&&t.In,f=h?document.createDocumentFragment():(d?t.root:t.sn).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 Ke(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.Re.length>0){let t=e.Un;if(null===u)s[t]=p;else for(let e of u)1===e.nodeType&&(e[t]=p)}let g=t.sr,y=e.Le,b=t.lr?a.slice(0,o.length):a,v=null===m?null:m.fe;if(null!==v){let e=t.ze;for(let t=0;t<e.length;t++)v[2*t]=b[e[t].a],v[2*t+1]=e[t].q}for(let r=0;r<g.length;r++){let i=g[r],o=b[i.a],l=i.A;if(l>=0&&null!==v){let r=m.V?.[l];if(void 0!==r){r.te=!1,e.Ve(r);continue}try{let t=$e(i.N,e.read(i.o,n));t!==i.q&&(qe(i.i,o,i.name,t),v[2*l+1]=t),null!==y&&e.po(i.o,n)}catch(t){e.$t(t,m.vo(e,l))}continue}switch(i.i){case 6:{let t=new it(e,i.F,Je(e,i.o,n,o),o);(p.c??=[]).push(t),o===s&&(p.Fn=t),t.Et();break}case 7:{let t=nt(e,i.G.map(e=>({F:e.F,o:e.o,N:e.N,S:b[e.a]})),n,p);(p.c??=[]).push(t),o===s&&(p.Fn=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.An,o=e=>s(e,r);if(n.et){let r=e.ao(n.name),i=t[r];t[r]=void 0===i?o:e=>{i(e),o(e)},n.$e&&t.addEventListener(n.name,e=>e.bubbles||o(e))}else t.addEventListener(n.name,o),n.yo&&null!==i&&(i.Nt??=[]).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.xt.slice(9)),l=null===i?c.or?.(n,s):null;l||(null===i&&Ie(1202,n,`command.${s}`),i.commands.has(s)||_(1203,[n.localName,s]));let a=new WeakRef(n),u=o.subscribe((...e)=>{let t=a.deref();if(void 0!==t)return t.isConnected?l?l(t,e):t[s](...e):void 0;u()});null!==r&&(r.Nt??=[]).push(u)}(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.xt;n.addEventListener(o.event,n=>{t.Rt&&n.preventDefault(),t.Pt&&n.stopPropagation();try{e.Zo(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.go?.includes(l))continue;let o=e.o(`${t.o.t}.${l}`),a=0===o.n?null:r;Me(e,{...t,U:null,Y:null},n,l,o,a,i,s)}}(e,t,s,l,i,n));if(t.$e&&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 Fe(e,1,n,t.name,t.o,r,i,t.N,De(e,t,r));o.j=t.j,!c.ar?.(o,t.ro)&&(Qe(e,o,!0),e.Ve(o))}(e,t,s,l,i,n));let a=new Fe(e,t.i,n,t.name,o,l,i,t.N,De(e,t,l));a.j=t.j,Qe(e,a,!0),e.Ve(a),null!==t.Tt&&n.addEventListener(t.Tt,()=>a.ir())}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 Fe(e,7,o.S,"if",t,X(n,t.n),r,null,void 0,i);Qe(e,l,!0),null===r&&i.ce.push(l),s??=l}return e.Ve(s),i}var rt=class{constructor(e,t,n){this.y=!0,this.O=null,this.b=-1,this.ce=[],this.engine=e,this.G=t,this.r=n}Cn(e){return null!==this.O&&this.G[this.b].S===e?this.O.Ke():null}Et(){let e=this.engine,t=-1;for(let n=0;n<this.G.length;n++){let r=this.G[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.wo(),this.O.Ne(e),this.O=null),this.b=t,t>=0)){let n=this.G[t],r=et(e,n.F,this.r,null,n.S);this.O=Ye();let i=n.S.parentNode;i.insertBefore(r,n.S),Ge(i)}}Ne(){this.y=!1;for(let e of this.ce)this.engine.xn(e);null!==this.O&&this.O.Ne(this.engine)}},it=class{constructor(e,t,n,r){this.y=!0,this.xe=[],this.engine=e,this.F=t,this.l=n,this.S=r,null===n.$?(n.$=this,this.map=null):((n.B??=[]).push(this),this.map=new Map)}Cn(e){return 0===this.xe.length?null:this.xe[0].Ke()}At(e){return null===this.map?e.$:this.map.get(e)??null}jt(e){let t=this.map;null!==t&&t.get(e.r)===e&&t.delete(e.r),e.Ne(this.engine)}Et(){let e=this.engine,t=this.l.f,n=this.xe;Ze=Te();let r=t.length,i=n.length,s=this.S,o=s.parentNode;if(0===r){if(i>0){let e=n[0].Ke(),t=n[i-1].s,r=[];for(let n=o.firstChild;null!==n;n=n===e?t.nextSibling:n.nextSibling)if(n!==e){if(n!==s&&3!==n.nodeType){r=null;break}r.push(n)}null!==r?o.replaceChildren(...r):ot(e,t);for(let e=0;e<i;e++)this.jt(n[e])}return void(this.xe=[])}let l=new Array(r),a=0;for(;a<r&&a<i&&this.At(t[a])===n[a];)l[a]=n[a],a++;let u=i-1,c=r-1;for(;u>=a&&c>=a&&this.At(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.At(r)===t?t.bo=e:(t.wo(),this.jt(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.At(t[a+e]);null!==n&&n.y?(u[e]=n.bo,h=!0):u[e]=-1}let d=c+1<r?l[c+1].Ke():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.At(n);null!==u&&u.y?0===r[s]&&u.insertBefore(o,i):(o.insertBefore(et(e,this.F,n,this),i),u=Ye()),l[a+s]=u,i=u.Ke()}}else{let n=document.createDocumentFragment();for(let r=a;r<=c;r++)n.appendChild(et(e,this.F,t[r],this)),l[r]=Ye();o.insertBefore(n,d)}}this.xe=l,Ge(o)}Ne(){this.y=!1;let e=this.l;if(e.$===this)e.$=null;else if(null!==e.B){let t=e.B.indexOf(this);t>=0&&e.B.splice(t,1),0===e.B.length&&(e.B=null)}for(let e of this.xe)e.Ne(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){for(let n,r=e;r!==t;r=n)n=r.nextSibling,r.remove();t.remove()}var lt=()=>ee.bindAttributeName;function at(){return{a:0,i:1,name:"",o:null,N:null,q:t,An:null,F:null,G:null,j:null,Tt:null,$e:!1,U:null,Y:null,ro:!1,Rt:!1,Pt:!1,xt:null,go:null,A:-1,et:!1,yo:!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.h[e];r.h[e]!==t&&_(1403,[r.t,r.h[e].t,t.t])}return c.So?.(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&&Ue(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.Wt||_(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"),Rt:t.includes("prevent"),Pt:t.includes("stop"),event:n?n.slice(2):null,U:r,Y:i}}(e,t.on),o=r.localName.includes("-"),l=t.Ee,a=t.Qe;if("event"===t.w){if(null!==s.U&&"none"!==s.U&&_(36),"eventToken"===l[0])return{...at(),a:i,i:13,name:l.slice(1).join("."),xt:a,$e:o,Rt:s.Rt,Pt:s.Pt};let n=a.startsWith(ht)?a.slice(9):null,{Rt:r,Pt:u}=s,c=t.Se.slice(2),h=t.on.includes("direct"),d=!h&&je.has(c);return d&&e.ao(c),{...at(),a:i,i:5,name:c,et:d,$e:o,yo:h,An(t,i){r&&t.preventDefault(),u&&t.stopPropagation();try{if(null!==n)e.er(n,t,i);else{let n=e.tr(a,t,i);K(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),$e:o};if("command"===l[0]&&l.length>1)return a.startsWith(ht)||_(1201,[t.Se,a]),{...at(),a:i,i:12,name:l.slice(1).join("."),xt:a,$e:o};let u=dt(e,a,n),c={...at(),a:i,i:1,name:t.Se,o:u,N:ke(t.Ze),j:ke(t.j),ro:s.ro,U:s.U,Y:s.Y};if("radio"===t.w||"checkbox"===t.w)return("element"===s.U||"auto"===s.U)&&_(37,[t.w,s.U]),c.i="radio"===t.w?9:10,s.ro||(c.Tt=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.U=null,c.name=e,"class"===t?(c.i=2,c.q=r.classList.contains(e)):c.i="attr"===t?"srcdoc"===e&&"iframe"===r.localName?1:3:4,c}return"html"===t.Se?(c.i=8,c):(c.name="text"===t.Se?"textContent":t.Se,c.$e=o&&!Ae(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.Tt=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].go=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,cr: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{Se:"textContent",Ee:["textContent"],on:[],j:[],...W(e),w:"text"}}(t);return{...at(),a:r,i:0,o:dt(e,i.Qe,n),N:ke(i.Ze),q:""}}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.Qe,n),N:"else"===r.w?null:ke(r.Ze)}),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.jn?.(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.Qe,n),s=Et(e,t,r,!0);i(a(t,ee.commentForPrefix),r,s)}else"if"===h.w?s($t(e,t,n).map((t,r)=>({F:Et(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.Eo?.(t);try{r&&m&&u([...t.childNodes])}finally{null!==p&&o(t,p)}!r&&m&&u([...t.childNodes])}else if(3===d.nodeType&&e.Mt&&d.data.includes("{{")&&!kt.has(d))for(let{a:e,cr: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*$/,At=e=>{let t=document.createRange();return t.selectNodeContents(e),e.content??t.cloneContents()};function Et(e,t,n,r){let i=document.importNode(At(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,F:n})},e=>{let t=e.map(e=>({a:l(e.S),F:e.F,o:e.o,N:e.N}));o.push({...at(),a:t[0].a,i:7,G: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.et&&!e.$e&&!Ct(s[e.a],i)){f.push(e);continue}p.push(e);let t=e.o;if(null!==t&&t.n===m&&t.h[m]===n&&xt(e)&&(e.A=h.push(e)-1),7===e.i)for(let t of e.G)d.add(t.a);else d.add(e.a)}let g=[...d].sort((e,t)=>e-t);return{sn:i,root:u?i.firstChild:null,On:a,build:g,Re:f,sr:p,In:u,lr:c,ko:[],ze: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.U)return!1;switch(e.i){case 0:case 2:case 3:case 4:case 8:return!0;case 1:return!e.$e&&null===e.Tt;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).Et()},t=>{nt(e,t,null,null)},(t,n)=>{c.jn?.(e,t,n);for(let r of n)tt(e,r,t,null,null)},(t,n)=>{c.jn?.(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 Ft=class{constructor(){this.name="dirty",this.Z=(e,r)=>{if(0===e.n){let r=e.z;return r!==t&&r!==n&&(e.z=n,!0)}let i=null===r?null:r.ht;if(null===i)return!1;let s=i[e.A];return s!==t&&s!==n&&(i[e.A]=n,!0)}}Jo(e,t,n){null!==t.getter&&this.Z(t,n),e.St(t,n),e.Nn(t,n,this.Z)}Ho(e,t){let n=t.l.o.Ct;if(null!==n)for(let r of n)r.n===t.l.n?e.it(r,t,this.Z):e.Zt(t,r,t=>e.it(r,t,this.Z))}we(e,t,n){this.Z(t,n),c.ve?.(e,t,n),e.St(t,n),e.Nn(t,n,this.Z)}Uo(e,i,s){let o=0===i.n;if(!o&&null===s)return;let l=o?null:s.ht??=new Array(e.Ie).fill(t),a=null===l?i.z:l[i.A];if(a!==t&&a!==n&&a!==r&&(null===l||i.A in l))return a;a=r;try{return a=e.qo(i,null===l?null:s)}finally{null===l?i.z=a:l[i.A]=a}}Xt(e){e.ht=null}bt(e){for(let t of e.I.all())null!==t.getter&&(0===t.n?t.z===n&&(t.z=r):e.tn(t.h[t.n],e=>{let i=e.ht;null!==i&&i[t.A]===n&&(i[t.A]=r)}))}},Ut=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 Gt(e){let t=qt.get(e)??[],n=t.filter(t=>t.getRootNode()===e);return Promise.any(n.map(e=>e.initializePromise.then(()=>e.V||e.connectedCallbackPromise))).then(()=>{},r=>n.length?qt.get(e)!==t?Gt(e):Promise.reject(r.errors[0]):void 0)}var Kt=typeof HTMLElement>"u"?class{}:HTMLElement,Vt=class extends Kt{constructor(){super(),this.engine=null,this.Ln=!1,this.Ue=!1,this.q=null,this.Xe=null,this.loaded=!1,this.cn=null,this.connectedCallbackPromise=new Promise((e,t)=>{this.an=e,this.$o=t}),this.connectedCallbackPromise.catch(()=>{}),this.initializePromise=new Promise(e=>{this.ln=e})}static{this.getBindingsReady=Gt}static{this.hasConnectedCallbackPromise=!0}connectedCallback(){if(this.Ln){if(null!==this.Xe)return void this.Xe.Ye();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.No("$connectedCallback",50,()=>{this.isConnected&&c.element?.(e,"connected")})}return}this.Ln=!0;let e=this.getRootNode(),t=c.at?.(this,e);if(t)return this.Xe=t,!t.xo&&this.parentNode instanceof ShadowRoot&&Bt(this),void(void 0===t.Dt?this.Ro():t.Dt()).then(e=>(this.loaded=!0,t.start(e,()=>this.Po()))).then(()=>{this.ln(),this.an()},e=>this.$t(e,t.xo));this.start(e),Bt(this)}disconnectedCallback(){if(null!==this.Xe)return void this.Xe.Bn();let e=this.engine;if(null===e)return;let t=e.root;Ot.get(t)===e&&Ot.delete(t),Bt(this,t),this.No("$disconnectedCallback",51),c.element?.(e,"disconnected")}setInitialState(e){if(this.Ue&&_(14),this.loaded)this.Xe.reset(e);else if(null===this.engine)if(null!==this.cn){let t=this.cn;this.cn=null,t(e)}else this.q=e;else this.engine.reset(e)}createState(e,t){let n=this.engine;null===n&&_(15),"readonly"===e&&n.je++;try{t(n.proxy)}finally{"readonly"===e&&n.je--}}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 Ro(){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//${++Ut}`);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.q?Promise.resolve(this.q):new Promise(e=>{this.cn=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.Ro(),r=y(n);if(r&&await r,this.getRootNode()!==e)return this.q=n,this.Ln=!1,void(this.isConnected&&this.connectedCallback());this.hasAttribute("enable-ssr")&&b("ssr","enable-ssr");let i=Ot.get(e)?.element;i?.isConnected&&(i.V||i.Xe)&&_(47);let s=new Z(n,new Ft);s.element=this,this.engine=s,c.element?.(s,"mounting"),Lt(s,e),Dt(),s.$n(),this.Po(),await s.ke("$connectedCallback"),this.isConnected&&c.element?.(s,"connected"),this.an()}catch(e){this.Ue=!this.V,this.$t(e)}}Po(){this.V=!0,this.ln()}$t(e,t){this.He(this.V?50:49,e),this.ln(),t?this.an():this.$o(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)}No(e,t,n){(async()=>this.engine.ke(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}).${!e.includes("-")&&t.startsWith("command.")?" A native element's command needs the add-on @wcstack/state/features/native-commands.":""}`,1203:(e,t)=>`<${e}> declares no command "${t}".`,1204:(e,t)=>`<${e}> declares no property "${t}".`,1205:(e,t,n)=>`<${e}> has no command "${t}" (a native <${e}>'s commands: ${n}).`,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"]),An=[[/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.']],En={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(En,e)?En[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 An){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.I.It(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.bt.has(t.s))return null;if(void 0===n){let n=Mn(r),s=i(t.d);for(let t of e.I.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.st?.(e,{type:"state:path-unresolved",source:i?"watch":"binding",path:r.t,missingSegment:t.seg});let u=e.I.It(o(r.t).o),h="";if(void 0!==u&&u!==r&&null!==u.getter){let e=u.h.slice(1).map((e,t)=>`for: ${0===t?e.t:e.t.slice(u.h[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)||!Ae(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 Fn(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 Un=[["$streams","$stream"],["$updatedCallback","$renderedCallback"]],qn={$trackDependency:"$dependOn",$untrackDependency:"$untracked"},Bn={name:"diagnostics",install(){c.Bo=Cn,c.Do=Sn,c.So=Rn,c.detail=Fn,c.Ue=h(c.Ue,zn);let e=c.de;c.de=(t,n)=>{(function(e){void 0!==e.$scan&&_(1);for(let[t,n]of Un)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.ot=d(p,c.ot,(e,t)=>Object.hasOwn(qn,t)?_(1701,[t,qn[t]]):void 0)}},Gn={},Kn=/\.\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.Q){for(let r of t)if(n.ee(r)&&(n.n===r.n||!(r.n<e.n&&e.h[r.n+1].ee(r))))return!0;null!==n.getter&&r.push(n)}}}return!1}var tr=class{constructor(e,t){this.active=!1,this.Ge=new Map,this.n=0,this.Ao=-1,this.Dn=new Set,this.We=null,this.engine=e,this.ct=t}ur(){let e=this.engine;this.Ge.clear();for(let t of this.ct)t.getter=null!==t.p.getter||t.p.se,t.s=new WeakMap,this.prime(t,()=>{0===t.p.n?t.getter&&t.s.set(Gn,e.v(t.p,null)):this.Mn(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.st?.(this.engine,{type:"state:watch-error",phase:"prime",path:e.t,error:t})}}Fo(){this.active=!1,this.Ge.clear()}Mn(e,t,n,r){let i=this.engine._e(n,e.h[t]);for(let n of i.f)t===e.n?r(n):this.Mn(e,t+1,n,r)}un(e,t,n,r){let i=this.Ge.get(e);void 0===i&&this.Ge.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)}be(e,t,n,r,i){if(this.active){(this.We??=new Set).add(e);for(let s of this.ct){let o=s.p;o.n!==e.n||!o.ee(e)||this.un(s,t,s.getter?s.s.get(t??Gn):o===e&&i&&this.engine._t&&(null===r||"object"!=typeof r&&"function"!=typeof r)?n:void 0,!0)}}}ve(e,t){if(this.active)for(let n of this.ct)(n.getter||=null!==n.p.getter||n.p.se)&&n.p.n===e.n&&n.p.ee(e)&&this.un(n,t,n.s.get(t??Gn),!1)}Jt(e,t){if(!this.active)return;let n=null;for(let r of this.ct){let i=r.p;if(!(i.n<e.n||i.h[e.n]!==e.o)){n??=new Set(t);for(let t of e.f)n.has(t)||(i.n===e.n?this.un(r,t,void 0,!0):this.Mn(i,e.n+1,t,e=>this.un(r,e,void 0,!0)))}}}Fe(){let e=this.We;if(this.We=null,!this.active||0===this.Ge.size)return;let t=this.Ge;this.Ge=new Map;let n=this.engine,r=[];for(let i of this.ct){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.u;this.n=a+1,n.Pe++;try{if(l=n.v(i.p,t),i.getter&&(i.s.set(t??Gn,l),Object.is(l,s)&&(Kn.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.u=t,c.st?.(n,{type:"state:watch-fired",path:i.t}),h="handler",i.handler.call(n.proxy,l,s,...n.H(t))}catch(e){console.error(`[@wcstack/state] $watch "${i.t}" failed; the other watches still run.`,e),c.st?.(n,{type:"state:watch-error",phase:h,path:i.t,error:e})}finally{n.u=d,this.n=0,n.Pe--}}}r.length>0&&this.Oo(r)}Oo(e){let t=Zn();t!==this.Ao&&(this.Ao=t,this.Dn.clear());let n=e.filter(e=>!this.Dn.has(e));if(0!==n.length){for(let e of n)this.Dn.add(e);console.error("[@wcstack/state] $watch handlers / $stream restarts kept writing for 32 batches; the chain is cut (nothing is rolled back)."),c.st?.(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.ae)n.unshift(t.b);for(let e=t;null!==e;e=e.l.ae)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.T(this.engine.o(`${e}.${t}`),null,n)}finally{lr=!1}}dr(){for(let e of this.entries)this.start(e,!0)}fr(){for(let e of this.entries)e.ut=!1,e.J?.abort(),e.J=null}pr(){for(let e of this.entries)e.ut=!1,null!==e.J&&(e.J.abort(),e.J=null),this.set(ir,e.name,"idle")}ve(e){let t=this.D.n;for(let n of this.entries)n.g===e&&(n.n=n.ut?Math.max(n.n,t):t,n.ut=!0)}Fe(){let e=this.engine,t=this.D,n=[];for(let i of this.entries){if(!i.ut)continue;let s=i.n;if(i.ut=!1,s>32)n.push(i.name),i.g.z=r;else{t.n=s+1,e.Pe++;try{this.start(i,!1)}finally{e.Pe--,t.n=0}}}n.length>0&&t.Oo(n)}start(e,t){let n,i=this.engine;if(null!==e.J&&e.J.abort(),e.J=null,null!==e.g){let s=e.g;s.getter=e.args;let o=s.Q.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.Q)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.Wn(s);if(s.z=r,t)throw n;return this.set(sr,e.name,n),void this.set(ir,e.name,"error")}}let s=new AbortController;e.J=s,i.T(i.o(e.name),null,e.q),this.set(sr,e.name,null),this.set(ir,e.name,"active"),this.mr(e,s,n)}async mr(e,t,n){let r=this.engine,i=t.signal,s=()=>!i.aborted&&e.J===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.q;try{let t=await e.source(n,i);if(!s())return;let l=t=>{c=void 0!==e.Co?e.Co(c,t):t,u(()=>r.T(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.J=null,u(()=>this.set(ir,e.name,"done"))}catch(n){if(!s())return;e.J=null,t.abort(),u(()=>{this.set(sr,e.name,n),this.set(ir,e.name,"error")})}}};function cr(e){for(let t of e.Q){let n=t.M.indexOf(e);n>=0&&t.M.splice(n,1),t.pt.delete(e)}e.Q.length=0,e.z=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.So?.(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,Co:u,q:h,J:null,ut:!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.Fo(),i.Ft.fr()),hr.set(e,{D:n,Ft:r,Ye:i?.Ye??!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.Ye="connected"===t),n.target===e.target)){if("disconnected"===t)return n.D.Fo(),void n.Ft.pr();n.Ye&&(n.D.ur(),n.Ft.dr())}}var mr=["$streamStatus","$streamError"],gr={name:"temporal",install(){c.de=h(c.de,fr),c.element=h(c.element,pr),c.be=h(c.be,(e,t,n,r,i,s)=>dr(e)?.D.be(t,n,r,i,s)),c.ve=h(c.ve,(e,t,n)=>{let r=dr(e);void 0!==r&&(r.D.ve(t,n),r.Ft.ve(t))}),c.Jt=h(c.Jt,(e,t,n)=>dr(e)?.D.Jt(t,n)),c.Fe=h(c.Fe,e=>{let t=dr(e);void 0!==t&&(t.D.Fe(),t.Ft.Fe())}),c.ot=d(p,c.ot,(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.Ae=d(f,c.Ae,(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.rt(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.T(t,n,l)}finally{br=!1}}if(c.length>0){let r=e._e(0===t.n?null:n,t);for(let[n,i,s]of c){if("__proto__"===i)continue;let o=r.f[n],l=vr.test(i)?e.o(`${t.t}.*.${i}`):null;null===l?.getter?e.T(l,o,s):(o.R[i]=s,e.T(e.o(`${t.t}.*`),o,o.R,!0))}}return!0}var Sr={name:"list-keys",install(){c.de=h(c.de,wr),c.Ae=d(f,c.Ae,kr)}},Nr=new WeakMap,Ar=new WeakMap,Er="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=Ar.get(e);return void 0!==t&&!Array.isArray(t)&&t.isConnected}function jr(e,t){let n=Ar.get(t);if(Ar.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.Je?.(),e.Je=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.rt(n,null)&&t.T(n,null,{})}t.T(t.o(e.t),null,l)}t.to(Object.defineProperties({},a));for(let e in a)t.We(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.Je?.(),e.Je=null}function Dr(e,t){let n=Ar.get(e);if(Array.isArray(n))for(let e of n)Hr(e,Er);Ar.set(e,t)}var Fr=new WeakMap;function Ur(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,Je: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=Ar.get(t);Array.isArray(e)&&Ar.set(t,e.filter(e=>e!==s)),s.Je?.(),s.Je=null}e.set(n,r)}}else i='has an invalid mount path: it must be a static path (no "*", "$", "#", "@").';return{xo:!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.Je=e;let n=Mr(Ot.get(t)),i=Ar.get(t);void 0!==n?zr(r,n):Ir(t)?Hr(r,Er):Ar.set(t,[...Array.isArray(i)?i:[],r])})}},Ye(){null!==r.engine&&Wr(r,"$connectedCallback")},Bn(){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 Gr(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 Kr(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=Gr(r,"$bindables"),o=Gr(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)},Ye(){},Bn(){},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)?.pe===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.V: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.dt.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.H(n),...i.H(X(i.u,t.n))]),null),s.rr)};t.getter=()=>{let e=a();return o.n>0&&null===e?void 0:s.v(o,e)},null!==o.ie&&(t.ie=n=>{let r=a();vi(e,l.e,()=>s.T(o,r,n)),e.dn=t}),t.n>0&&(t.A=i.Ie++),e.dt.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.me}else{if(null===t||null!==n.d||"$"===o[0]||pi(i,o))return;l=t,r=s.o(`${t.me.t}.${o}`)}let a=l.r,u=l;n.getter=()=>s.v(r,bi(e,a)),n.ie=t=>{vi(e,u,()=>s.T(r,a,t)),e.dn=n},e.dt.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.fn===t||null===e.host.engine)return;e.fn=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.fe){let e=r.get(n.e.me);void 0===e&&r.set(n.e.me,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.re&&function(e,t){let n=e.host,r=n.engine;e.re=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.me.t}.${o}`);if(null===u.getter)Si(r,u,t.me);else if(!$i.has(u.getter))continue;e.re.set(u,e.x.o(o))}}(e,i);for(let r of e.re.keys())t&&null===r.getter&&Si(n,r,i.me),n.P.we(n,r,i.r);e.re.size>0&&n.Te(),t&&function(e,t){let n=e.host.engine;for(let[r,i]of e.re){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.pe}.${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.re?.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.u);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.u,t);return null===o?void 0:o.x.read(o.re.get(t),null)},$i.add(t.getter),t.ie=o=>{let l=null===s()?ki(e,n,e.u,t):null;if(null===l){let t=e.read(r,e.u);return void(null!==t&&"object"==typeof t&&(t[i]=o))}let a=l.re.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.T(a,null,o)},t.n>0&&(t.A=e.Ie++)}function Ni(e,t,n,r,i,s){if(null!==t.getter)return e.P.we(e,t,n),void e.Te();if("*"===t.s){if(null===n)return;if(n.R=n.l.C[n.b],e.P.Xt(n),null!==n.c)for(let t of n.c.values())e.Y(t)}else e.En(t,n);c.be?.(e,t,n,r,i,s),e.We(t,n)}function Ai(e){let t=e.m.x;for(let[n,r]of e.m.dt)r.e===e.e&&(0===n.n?t.P.we(t,n,null):t.tn(n.h[n.n],e=>t.P.we(t,n,e)));t.Te()}function Ei(e,t,n,r,i,s,o){let l=n.t.slice(t.t.length);if(""===l)return Ai(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.fn&&!ri.has(l.host.engine)&&function(e,t,n,r,i,s){let o,l=t;for(;null!==l&&void 0===(o=e.dt.get(l));)l=l.d;if(null===l||void 0===o)return;let a=e.host.engine;if(l===t&&e.dn===t)return void(e.dn=null);if(null!==o.r&&!o.r.y)return;let u=[...a.H(o.r),...e.x.H(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.fn&&null!==l.re&&function(e,t){let n=e.host.entries.find(e=>""===e.E),r=e.host.engine;for(let[i,s]of e.re)s===t&&(r.P.we(r,i,n.r),r.Te())}(l,t);let a=ti.get(e);if(void 0===a)return;for(let[e,l]of a)if(t.ee(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)&&Ei(l,e,t,n,r,i,s)}else if(e.ee(t))for(let[e,r]of[...l])if(0===t.n||X(e,t.n)===n)for(let e of[...r])wi(e,o)&&Ai(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.pe}">.`),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.Cn(t);null!==n&&n!==t;n=n.nextSibling)l(n);l(t)};for(let e of r.ce.values())for(let t of e)if(null===t.W)l(t.a);else for(let e of t.W.G)a(t.W,e.S);for(let e of r.oe.values())for(let t of[e.$,...e.B??[]])null!==t&&a(t,t.S);for(let t of e.L)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.L.includes(n)&&(s(n)||r.Mt&&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.L=e.L.filter(e=>e.parentNode===n),t.isConnected?await Ti(e,r):r()}(l,e,n,i);let a=new Z(r,new Ft);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.V=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,L:[],x:a,host:o,fe:[],dt:new Map,fn:!1,dn:null,from:null,re:null};for(let e of o.entries)u.fe.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.pe}.${e.E}" is hidden by the component's own "${t}"; rename one side.`)}if(null!==s){let e=r.v(s.me,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.me.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.pe}$`,`[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.nt;t.nt=n=>{yi(e,s,n),l.call(t,n)};let a=[...t.I.all()];for(let t of a)yi(e,s,t);for(let e of a)l.call(t,e);let u=t.zt;t.zt=()=>{(function(e){for(;void 0!==e;e=ei.get(e.host.engine))if(e.host.entries.some(e=>null!==e.r&&!e.r.y))return!1;return!0})(e)&&u.call(t)}}(u),_i(u,!0),Cr.add(a),jr(a,n));let d=c.hr?.(n);Lt(a,n),d?.(),u.L=[...n.childNodes],Dt(),h&&a.$n(),Object.defineProperty(t,o.pe,{configurable:!0,enumerable:!0,get:()=>a.proxy});let f=t.$stateReadyCallback;if("function"==typeof f)try{let e=f.call(t,o.pe);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.ke("$connectedCallback"),h&&e.isConnected&&c.element?.(a,"connected")):_i(u,!1)}async function Ti(e,t){_i(e,!0);for(let t of e.fe)Ai(t);t?.(),!e.broken&&(await e.x.ke("$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.V||void 0!==n&&n!==e&&n.isConnected)){Dr(t,e);for(let e of Fr.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{Dt:()=>(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.pe!==t&&v(`<${i}> already has a <${ee.tagNames.state} bind-component="${s.pe}">.`),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=Fr.get(e)??new Set;return Fr.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,me:e.o,r:e.r,ro:Jr.has(e)}),e.engine.xn(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,pe: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)})},Ye(){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)},Bn(){let e=o();null!==e&&(_i(e,!1),!e.broken&&(e.x.ke("$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.at=d(m,c.at,Ur),c.at=d(m,c.at,Kr),c.at=d(m,c.at,Pi),c.ar=ai,c.Eo=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.be=h(c.be,(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.ve=h(c.ve,(e,t,n)=>Ci(e,t,n,void 0,void 0,!1,!0)),c.Ae=d(f,c.Ae,(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.dt.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.pe}${""===s.E?"":`.${s.E}`}#ro: ${s.me.t}"). Write it on the host, or drop #ro from the mount.`)))}(e,t,i)));let e=c.de;c.de=(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 Fi(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 Ui(e,t,n){let r=Fi(e,t),i=function(e,t){for(let n=t;null!==n;n=n.l.ae){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._e(a,i).f,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._e(null,l).f,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.nt;t.nt=r=>{let i=Mi.get(e);if(r.t.includes("**")){let t=e.I.It(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.A=t.Ie++),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("**")?Ui(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,Ui(s,n,t.u));(!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=Fi(s,n),l=[];return qi(e,s,(t,n)=>{for(let r of i.call(e,Di(s,t)+o,e.H(n)))l.push(r)}),l};let s=t.yn;t.yn=(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.je>0&&_(8);let a=Fi(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.H(n),i);return d}}(e)):r&&(Mi.delete(e),Ri--)}function Gi(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 Ki={name:"recursion",install(){c.de=h(c.de,Bi),c.element=h(c.element,(e,t)=>{("mounting"===t||"reset"===t)&&function(e){ji.delete(e)}(e)}),c.Ae=d(f,c.Ae,Gi)}},Vi="4.0.0-rc.7",Ji=e=>e.split(".").slice(0,2).join("."),Qi=class extends Kt{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.L?e.qe:e.L[e.L.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.qe,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.xe,null);for(let t of e.xe)ps(t);return}let t=e.O;null!==t&&(ds(e.G[e.G.length-1].S,[t],e.b),ps(t))}function ps(e){if(null!==e.c)for(let t of e.c)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.oe.values())if(null!==t.$&&n.set(t.$.S,t.$),null!==t.B)for(let e of t.B)n.set(e.S,e);for(let t of e.ce.values())for(let e of t)if(null!==e.W)for(let t of e.W.G)n.set(t.S,e.W);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(At(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.Eo?.(e),As=e=>1===e.nodeType&&!ys(e)&&!Ns(e),Es=e=>e.f.flat().concat(e.K??[]),Cs=e=>{for(let t of Es(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),As(l)&&Ts(l,t))}l=e}let a={branch:void 0===r[1]?null:Number(r[1]),f:o,K:l??s.appendChild(ts("wcs-]"))},u=Es(a);l=a.K.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):(As(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,Oe: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.Oe),!t.Oe))return null;let n=c.Oe;return c.Oe=Ds,()=>{c.Oe=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)?.K??e).nextSibling;function zs(e,t){if(t.length!==e.sn.childNodes.length)return!1;let n=e.On;for(let r=0;r<n.length;r++){let i=n[r],s=e.sn,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.ko[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.f.shift();if(0===s.f.length&&ks.delete(r),s.K?.replaceWith(...us(t,r)),s.K=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.K;)e++}if(!zs(e,l)){let n=(e.In?e.root:e.sn).cloneNode(!0);l=e.In?[n]:[...n.childNodes],zs(e,l),(o[0]??s.f.find(e=>e.length>0)?.[0]??t).before(n);for(let e of o)e.remove()}return l}var Fs={name:"ssr",install(){c.jn=js,c.hr=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.ke;t.ke=(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.Qe;r.Ee[0]===s&&n.push([e?Is(e,t,1,0):t,r.Ee.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.Oe=Ds,queueMicrotask(()=>{Ls(),c.Oe=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.To=h(c.To,Xi);for(let e of Qt())Xi(e)}},Us="__WCSTACK_DEVTOOLS_HOOK__",qs=null,Bs=new Set,Gs=(e,t,n)=>({absolutePathInfo:{pathInfo:{path:t.t},stateElement:e.element},listIndex:null===n?null:{indexes:e.H(n)}}),Ks=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=Ks.get(e);return void 0===t&&Ks.set(e,t=++Vs),t})(s)}|${u}|${o.t}|${null===c?"":e.H(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:Gs(e,o,c)})},s=e=>i(e.i,e.name,e.a,e.o,e.r,e.nn()),o=e=>{if(!r.has(e)){if(r.add(e),null!==e.he)for(let t of e.he)s(t);if(e instanceof Ve&&null!==e.fe){let t=e.F.ze;for(let n=0;n<t.length;n++){let r=e.V?.[n];void 0!==r?s(r):i(t[n].i,t[n].name,e.fe[2*n],t[n].o,e.r,0===t[n].i?"text":"prop")}}if(null!==e.c)for(let t of e.c)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.ae,"for");for(let t of e.xe)o(t)}else null!==e.O&&o(e.O)};for(let t of e.ce.values())for(let e of t)s(e),null!==e.W&&l(e.W);for(let t of e.oe.values())if(null!==t.$&&l(t.$),null!==t.B)for(let e of t.B)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.I.all()){for(let e=1;e<=s.n;e++)t.add(s.h[e].t);"*"===s.s&&n.add(s.t),null!==s.getter&&r.add(s.t),null!==s.ie&&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.Re.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.Re.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=Gs(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.nn(),error:t})}var so={"*":["focus","blur","click","scrollIntoView","showPopover","hidePopover","togglePopover"],dialog:["show","showModal","close","requestClose"],form:["requestSubmit","checkValidity","reportValidity"],input:["select","setSelectionRange","showPicker","setCustomValidity","checkValidity","reportValidity"],textarea:["select","setSelectionRange","setCustomValidity","checkValidity","reportValidity"],select:["showPicker","setCustomValidity","checkValidity","reportValidity"],audio:["play","pause","load"],video:["play","pause","load"]};function oo(e,t){let n=e.localName;if(n.includes("-"))return null;let r=(e=>[...so["*"],...Object.hasOwn(so,e)?so[e]:[]])(n);return r.includes(t)||_(1205,[n,t,r.join(", ")],t,r),(e,n)=>e[t](...n[0]instanceof Event?[]:n)}!function(e){for(let t of e)g.has(t.name)||(g.add(t.name),t.install())}([pn,Bn,gr,Sr,Oi,Ki,Fs,{name:"devtools",install(){c.element=h(c.element,to),c.be=h(c.be,no),c.Fe=h(c.Fe,ro),c.Ue=h(c.Ue,io),function(){if(typeof document>"u"||document.documentElement?.hasAttribute("data-wcs-server"))return;let e=globalThis,t=e[Us]??(e[Us]=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.I.all()){let r=n._,i=n.Ce?.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.st=e&&((e,t)=>qs?.({...t,stateElement:e.element})),t&&queueMicrotask(()=>{for(let e of Bs)Qs(e)})}})}()}},{name:"native-commands",install(){c.or=oo}}]),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.To?.(e)}();const lo={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"},ao=!1,uo=[".html"];function co(){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 ho(e,t){if(t&&"cause"in t)throw new Error(`[@wcstack/router] ${e}`,{cause:t.cause});throw new Error(`[@wcstack/router] ${e}`)}let fo=class extends Error{fallbackPath;constructor(e,t){super(e),this.fallbackPath=t}};const po={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 mo(e){const t={};for(const[n,r]of new URLSearchParams(e))t[n]=r;return Object.freeze(t)}function go(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 yo={static:2,param:1,"catch-all":0};let bo=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&&ho(`${lo.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&ho(`${lo.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+=yo[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(po).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||ho(`${lo.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:mo(e.search??""),routeName:e.routes[e.routes.length-1]?.name??""})}(e));if("string"==typeof r&&""!==r)throw new fo("Navigation cancelled by guard.",r);if(!r)throw new fo("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof r?r:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new fo("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}};const vo="data-wcs-ssr",wo="data-wcs-ssr-link",_o="@@wcs-route-ph:",$o="@@wcs-route-start:",ko="@@wcs-route-end:";let So=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=co();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new bo(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||ho(`${lo.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(`${ko}${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):ho(`${lo.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&&ho(`${lo.route} with fallback attribute must be a direct child of ${lo.router}.`),e.fallbackRoute&&ho(`${lo.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 No=Symbol.for("wcstack.trustedTypes.policy"),Ao=Symbol.for("wcstack.trustedTypes.internal"),Eo="wcstack";function Co(){const e=globalThis[No];return null===e||"object"!=typeof e?null:e}let xo=!1;function To(e){const t=function(){const e=globalThis,t=e[Ao];if(void 0!==t)return t;const n=globalThis.trustedTypes;let r=null;if(n&&"function"==typeof n.createPolicy)try{r=n.createPolicy(Eo,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){"function"!=typeof Co()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${Eo}". Allow it in the CSP (\`trusted-types ${Eo};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,e)}return e[Ao]=r,r}(),n=t?.createHTML;if("function"==typeof n)return n.call(t,e);if(!("trustedTypes"in globalThis))return e;const r=Co(),i=r?.createHTML;return"function"==typeof i?(xo||(xo=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${Eo}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${Eo};\` in the CSP to avoid this. See docs/csp.md section 7.`)),i.call(r,e)):e}const Po=new Map;let Oo=class extends HTMLElement{_uuid=co();constructor(){super()}async _loadTemplateFromSource(e){try{const t=await fetch(e);t.ok||ho(`${lo.layout} failed to fetch layout from source: ${e}, status: ${t.status}`);const n=await t.text();return Po.set(e,n),n}catch(t){ho(`${lo.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(`${lo.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(e)Po.has(e)?n.innerHTML=To(Po.get(e)||""):n.innerHTML=To(await this._loadTemplateFromSource(e)||"");else if(t){const e=this._loadTemplateFromDocument(t);e?n.innerHTML=To(e):console.warn(`${lo.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")&&ao}get name(){return this.getAttribute("name")||""}};class Lo extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||ho(`${lo.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")&&ao}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const Mo=new Set(["props","states","attr",""]);function Io(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 jo(e,t){e.hasAttribute("data-bind")||ho(`${e.tagName} has no 'data-bind' attribute.`);const n=e.getAttribute("data-bind")||"";Mo.has(n)||ho(`${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&&Io(e,t,r)}).catch(()=>{ho(`Failed to define custom element: ${i}`)}):Io(e,t,r)}const Ro=Symbol.for("wcstack.binder");function Ho(){const e=globalThis[Ro];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}const Wo=Symbol.for("wcstack.binder.pending"),zo=Symbol.for("wcstack.binder.taken");function Do(){const e=globalThis;let t=e[zo];return void 0===t&&(t=new WeakSet,e[zo]=t),t}function Fo(e,t){const n=Ho();return null===n?(function(){const e=globalThis;let t=e[Wo];return void 0===t&&(t=[],e[Wo]=t),t}().push(e),!1):(Do().add(e),n.bind(e,t),!0)}const Uo={range:!0};function qo(e,t){for(const n of e.routeChildNodes)t.add(n.placeHolder).add(n.endMarker),qo(n,t);return t}function Bo(e){const t=e.placeHolder,n=e.endMarker,r=null!==n.parentNode&&n.parentNode===t.parentNode&&!!(4&t.compareDocumentPosition(n)),i=r?null:qo(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 Go=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||ho(`${lo.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(`${lo.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!==Ho())for(const t of e)1===t.nodeType&&Fo(t,Uo)}(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=>{jo(t,e)}),t.hasAttribute("data-bind")&&jo(t,e))}};function Ko(){return document.createElement(lo.layoutOutlet)}const Vo="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)),ho(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 ${Vo}`:`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 ${Vo}`}(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 Qo(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 Xo(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===lo.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),Qo(r,a),n.push(a),o=a.placeHolder,l=a}else{if(a===lo.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===lo.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=Ko();r.layout=n,o=r,l=t}}const u=await Xo(e,l,n,r);l.replaceChildren(),l.appendChild(u),s.appendChild(o)}else s.appendChild(t);return s}async function Yo(e){const t=new Map;return await Xo(e,e.template.content,[],t)}function Zo(e){return!1!==e.checkVisibility?.()}function el(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=po[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)el(i,t,n,r)}function tl(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)el(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 nl=null,rl=null;function il(){const e=uo;return 0===e.length?null:(nl===e&&rl||(nl=e,rl=new RegExp(`\\/[^/]+(?:${e.map(e=>e.replace(/\./g,"\\.")).join("|")})$`,"i")),rl)}function sl(e){let t=e||"/";t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/");const n=il();return n&&(t=t.replace(n,"")),""===t&&(t="/"),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function ol(e,t){let n=e;return""!==t&&(e===t?n="":e.startsWith(t+"/")&&(n=e.slice(t.length))),""===n?"/":n}function ll(e){let t=e||"";if(!t)return"";t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/");const n=il();return n&&(t=t.replace(n,"")),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),"/"===t?"":t}function al(e){if(null!==e.held)return;const t=Bo(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 ul(e){e.clearParams(),al(e)}function cl(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=>{jo(t,e.typedParams)}),n.hasAttribute("data-bind")&&jo(n,e.typedParams),n.querySelectorAll(lo.layoutOutlet).forEach(t=>{t.assignParams(e.typedParams)}),n.tagName.toLowerCase()===lo.layoutOutlet&&n.assignParams(e.typedParams)}}const hl=new WeakSet;function dl(e){const t=e.placeHolder;null!==t.parentNode&&(hl.has(e)||null!==e.endMarker.parentNode?(al(e),t.after(e.held),e.held=null):t.after(...e.childNodeArray,e.endMarker),hl.add(e))}const fl=Symbol.for("wcstack.transition-runner");const pl=new WeakSet,ml="data-wcs";function gl(e,t,n){!pl.has(e)&&function(e){return e.hasAttribute(ml)||null!==e.querySelector(`[${ml}]`)}(e)&&(pl.add(e),function(e){"complete"===document.readyState?e():window.addEventListener("load",e,{once:!0})}(()=>{var r;null!==Ho()||(r=e,Do().has(r))||console.warn(`[@wcstack/router] ${t} contains ${ml} 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 yl(e){for(const t of e.childNodeArray)if(1===t.nodeType){if(t.isConnected){if(Fo(t,Uo))continue}else if(null!==Ho())continue;gl(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 bl(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 fo)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 vl(e,t,n,r,i=""){const s=ol(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=tl(e,s);o||(e.fallbackRoute?o={routes:[e.fallbackRoute],params:{},typedParams:{},path:s,lastPath:r}:ho(`${lo.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 bl(e,t))return!1;const r=new Set(t.routes),i=new Set(n),s=()=>{for(const e of n)r.has(e)||ul(e);const e=[];for(const n of t.routes)(e.length>0||!i.has(n)||n.shouldChange(t.params))&&(e.push(n),cl(n,t));let s=!1;for(const t of e){const e=i.has(t);e&&s||dl(t),s||=e,n.length>0&&!e&&yl(t)}};let o;return 0===n.length?s():o=function(e,t,n){const r=function(e){const t=globalThis[fl];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 wl(){const e=window.navigation;return e?"function"!=typeof e.addEventListener||"function"!=typeof e.removeEventListener?null:e:null}function _l(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 $l(e){return"?"===e?"":e}function kl(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 Sl(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const Nl=Object.freeze({});class Al 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=Nl;_typedParams=Nl;_searchParams=Nl;_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 sl(e)}_normalizeBasename(e){return ll(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(lo.outlet))return e;const t=document.createElement(lo.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||ho(`${lo.router} has no outlet.`),this._outlet}get template(){return this._template||ho(`${lo.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=mo(e.search),i=e.data??null,s=this._data!==i,o=!go(this._params,t),l=this._routeName!==e.routeName,a=!go(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(`${lo.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(`${lo.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=_l(e),r=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,i=r+$l(n.search)+n.hash,s=wl();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(ol(e,this._basename));await vl(this,this.outlet,e,this._path,$l(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(ol(n,this._basename)),i=r&&("push"===e.navigationType||"replace"===e.navigationType),s=t.search,o=this;e.intercept({handler:async()=>{try{await vl(o,o.outlet,n,o.path,s)}catch(e){throw console.error(`${lo.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 vl(this,this.outlet,e,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const e=Sl();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||ho(`${lo.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||ho(`${lo.router} should have a <template> child element.`);const r=e?this._template.content.cloneNode(!0):null,i=await Yo(this),s=!e&&this._outlet.hasAttribute(vo);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&&ho(`${lo.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(vo);const e=this._outlet.rootNode;for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(i)}await vl(this,this.outlet,o,this._path,window.location.search||""),(s||null!==Ho())&&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(lo.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(_o)){const r=t.slice(15);if(i.has(r)||!n.has(r))return!1;i.set(r,e)}else if(t.startsWith($o)){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(ko)){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=ol(e,this._basename);let h=tl(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($o)){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()===lo.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(vo);for(const e of h.routes)cl(e,h);return this.outlet.lastRoutes=h.routes,!await bl(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=ol(e,this._basename),n=tl(this,t),r=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===r.length&&ho(`${lo.router} No route matched for path: ${t}`),!r.some(e=>e.hasGuard)){await vl(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(e=>{e.placeHolder.data=`${_o}${e.absolutePath}`}),this.outlet.setAttribute(vo,"");for(const e of this.outlet.lastRoutes)e.placeHolder.after(document.createComment(`${$o}${e.absolutePath}`))}}_offerInitialContentToBinder(){for(const e of this.outlet.lastRoutes)for(const t of e.childNodeArray)t.nodeType===Node.ELEMENT_NODE&&t.isConnected&&Fo(t,Uo)}_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(!kl(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),Sl()){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=wl();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&&(wl()?.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 El=["title","rel","target","download","hreflang","lang","dir"];class Cl extends HTMLElement{static get observedAttributes(){return["to",...El]}_childNodeArray=[];_uuid=co();_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(lo.router);if(e)return this._router=e;const t=this.getRootNode(),n=t.querySelector?.(lo.router);if(n)return this._router=n;ho(`${lo.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 sl(e)}_joinInternalPath(e,t){const n=ll(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}=_l(t),s=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);e.href=s+$l(r)+i}else try{e.href=new URL(t).toString()}catch{ho(`[${lo.link}] Invalid URL in 'to' attribute: ${t}`)}}connectedCallback(){Sl()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const e=this.nextElementSibling;return null!==e&&"A"===e.tagName&&e.hasAttribute(wo)?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(wo),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-")||El.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,Sl())return this._updateActiveState(),void n.setAttribute(wo,"");wl()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!wl()?.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(){wl()?.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(El.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}=_l(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 xl=[],Tl=new Map;let Pl=!1;const Ol=new WeakMap;class Ll 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(),Pl||(this._captureInitialHead(),Pl=!0),xl.push(this),this._reapplyHead()}disconnectedCallback(){const e=xl.indexOf(this);-1!==e&&xl.splice(e,1),this._reapplyHead()}get childElementArray(){return this._initialized||ho("Head component is not initialized yet."),this._childElementArray}_getKey(e){const t=Ol.get(e);if(void 0!==t)return t;const n=this._computeKey(e);return Ol.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);Tl.has(e)||Tl.set(e,t.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of xl)for(const n of t._childElementArray)e.add(this._getKey(n));for(const t of Tl.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=xl.length-1;t>=0;t--){const r=xl[t];for(const t of r._childElementArray)if(this._getKey(t)===n){e=t.cloneNode(!0);break}if(e)break}!e&&Tl.has(n)&&(e=Tl.get(n).cloneNode(!0));const r=t.get(n)??null;e?(r?r.replaceWith(e):document.head.appendChild(e),t.set(n,e),Fo(e)||gl(e,`<${e.tagName.toLowerCase()}> inside <${lo.head}>`,`<${lo.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(lo.layout)||e.define(lo.layout,Oo),e.get(lo.layoutOutlet)||e.define(lo.layoutOutlet,Go),e.get(lo.outlet)||e.define(lo.outlet,Lo),e.get(lo.route)||e.define(lo.route,So),e.get(lo.router)||e.define(lo.router,Al),e.get(lo.link)||e.define(lo.link,Cl),e.get(lo.head)||e.define(lo.head,Ll)}(void 0);const Ml="data-fetchtarget",Il={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let jl=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 Rl(e,t){return t.every(t=>"available"===e.availability.get(t))}const Hl=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let Wl=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 jl("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 Rl(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}}(Hl,{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(!Rl(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)}}},zl=!1;function Dl(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest(`[${Ml}]`);if(!n)return;const r=n.getAttribute(Ml);if(!r)return;const i=customElements.get(Il.fetch),s=document.getElementById(r);if(!(i&&s instanceof i))return;const o=s;o.url&&(e.preventDefault(),o.fetch())}function Fl(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 Ul=Symbol.for("wcstack.trustedTypes.policy");function ql(){const e=globalThis[Ul];return null===e||"object"!=typeof e?null:e}let Bl,Gl=!1;let Kl=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Wl.wcBindable,properties:[...Wl.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 Wl(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(Il.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(Il.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=ql(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(t)}catch(e){if(function(){if(void 0!==Bl)return Bl;if(!("trustedTypes"in globalThis))return Bl=!1,Bl;try{document.createElement("div").innerHTML="<i></i>",Bl=!1}catch{Bl=!0}return Bl}())return void function(){if(Gl)return;Gl=!0;const e="function"==typeof ql()?.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(!Fl(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this.style.display="none",zl||(zl=!0,document.addEventListener("click",Dl)),!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 Vl 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 Ql=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 Kl&&(e.loading||(e.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(e=customElements){e.get(Il.fetch)||e.define(Il.fetch,Kl),e.get(Il.fetchHeader)||e.define(Il.fetchHeader,Vl),e.get(Il.fetchBody)||e.define(Il.fetchBody,Jl),e.get(Il.infiniteScroll)||e.define(Il.infiniteScroll,Ql)}(void 0);const Xl="data-storagetarget",Yl={storage:"wcs-storage"},Zl="wcs-storage:value-changed",ea="wcs-storage:loading-changed",ta="wcs-storage:error",na="wcs-storage:error-info-changed",ra="wcs-storage:trigger-changed";let ia=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:Zl,semantics:"state",getter:e=>e.detail},{name:"loading",event:ea,semantics:"state"},{name:"error",event:ta,semantics:"state"},{name:"errorInfo",event:na,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(ea,{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(ta,{detail:e,bubbles:!0})))}_commitErrorInfo(e){this._errorInfo=e,this._target.dispatchEvent(new CustomEvent(na,{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)}},sa=!1;function oa(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest(`[${Xl}]`);if(!n)return;const r=n.getAttribute(Xl);if(!r)return;const i=customElements.get(Yl.storage),s=document.getElementById(r);i&&s instanceof i&&(e.preventDefault(),s.save())}function la(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 aa=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...ia.wcBindable,properties:[...ia.wcBindable.properties,{name:"trigger",event:ra,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 ia(this),this._internals=this._initInternals(),this._wireStates({[ea]:e=>({loading:!0===e}),[ta]: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(ra,{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(!la(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this.style.display="none",sa||(sa=!0,document.addEventListener("click",oa)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(e=customElements){e.get(Yl.storage)||e.define(Yl.storage,aa)}(void 0);const ua="*",ca="vanilla",ha={loaders:{[ca]:{postfix:".js",loader:async function(e){return(await(import(`${e}`))).default}},[ua]:ca},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function da(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 fa(e,t,n){let r;if(null===t||t===ua||""===t){let t=null;const i=[];for(const[e,t]of Object.entries(n)){if(e===ua)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[ua],"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 pa=new Set,ma=new Map;let ga=new WeakMap;function ya(e){if(e===globalThis.customElements)return ma;let t=ga.get(e);return void 0===t&&(t=new Map,ga.set(e,t)),t}const ba=new Map;async function va(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 ba)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){pa.has(t)||(console.error(`Failed to eager load component '${t}':`,e),pa.add(t))}}function wa(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 _a(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&&ba.set(e,t)});const $a=new WeakSet,ka=new WeakSet;async function Sa(e,t,n){e.shadowRoot&&($a.has(e)||await async function(e,t,n){$a.add(e),await Ca(e.shadowRoot,t,n)}(e,t,n))}async function Na(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=ya(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=fa("",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),pa.add(e.name)}}(e,t,i,r);s.set(e.name,l);try{await l}finally{s.delete(e.name)}}async function Aa(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=_a(e);void 0===r.get(i.name)?(ka.has(e)||(ka.add(e),r.whenDefined(i.name).then(async()=>{await Sa(e,t,n)})),l.has(i.name)||pa.has(i.name)||(l.add(i.name),o.push(i))):await Sa(e,t,n)}let a=0;for(const e of o)await Na(e,t,n,r),a++;return a}async function Ea(e,t,n,r){for(;await Aa(e,t,n,r)>0;);}async function Ca(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 wa(t)}return wa(globalThis.customElements)}(e);if(null===r)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await Ea(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 Ea(e,t,n,r)}catch(e){console.error("Failed to lazy load components: "+e)}});return i.observe(e,{childList:!0,subtree:!0}),i}class xa extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),xa._instance)throw new Error(`${ha.tagNames.autoloader} can only be instantiated once.`);xa._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=da(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=fa(i.key,i.loaderKey,t)}catch(e){throw new Error("Loader redirection is not supported for eager loaded components: "+r)}n.push(va(i,r,s))}await Promise.all(n)}(n,ha.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 Ca(document,ha,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,xa._instance===this&&(xa._instance=null)}}!function(e=customElements){e.get(ha.tagNames.autoloader)||e.define(ha.tagNames.autoloader,xa)}(void 0);
|
|
2
2
|
//# sourceMappingURL=auto.min.js.map
|