wcstack 4.1.1 → 4.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/package.json +1 -1
package/dist/auto.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=class{constructor(e,n,r){this.c=[],this.getter=null,this.ie=null,this.se=!1,this.W=[],this.J=[],this.ft=null,this.A=-1,this.z=t,this.Ie=null,this.Ct=null,this.It=null,this._=null,this.pn=!1,this.mn=!1,this.Wn=!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}_n(e){this.pt.has(e)||(this.pt.add(e),this.W.push(e),e.J.push(this))}Io(e){this.pt.delete(e);let t=this.W;t.splice(t.indexOf(e),1)}jo(){this.getter=null,this.ie=null,this.A=-1,this.z=t,this.W.length=0,this.pt.clear(),this.J.length=0,this.ft=null,this.Ie=null,this.Ct=null,this.It=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}jt(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()}Lt(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.D=null,this.te=!1,this.Bt=!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.Mt&&Array.isArray(t)){let e=t.filter(e=>!g.has(e));if(e.length>0)return c.Mt(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 C(e,t,n){let r=N(e);if(null!==r)return r.run(t,{source:e,types:n});t()}var E="else",A="eventToken",x="class",T="attr",P=/^\$[1-9]\d{0,2}$/,O=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function M(e){let t=[],n=[],r="",i=null,s=!1,o=-1,l=-1,a=e=>{let i=function(e,t,n){let r=-1===t?e.length:t,i=-1===n?0:n;return e.slice(r-e.slice(0,r).trimStart().length,i+e.slice(i).trimEnd().length)}(r,o,l);(!e||i||s)&&(t.push(i),n.push(function(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:O.test(e)?Number(e):e)}(i,s))),r="",s=!1,o=-1,l=-1};for(let t=0;t<e.length;t++){let n=e[t];i?n===i?i=null:(-1===o&&(o=r.length),r+=n,l=r.length):'"'===n||"'"===n?(i=n,s=!0):","===n?a():r+=n}return null!==i&&_(107,[i,e]),a(!0),{args:t,literals:n}}var L=e=>e.trim();function I(e,t){let n=[],r=null;for(let i=0;i<e.length;i++){let s=e[i];null!==r?s===r&&(r=null):"'"===s||'"'===s?r=s:s===t&&n.push(i)}return n}var j=(e,t)=>I(e,t)[0]??-1;function R(e,t){let n=[],r=0;for(let i of I(e,t))n.push(e.slice(r,i)),r=i+1;return n.push(e.slice(r)),n}function H(e,t,n){let r=j(e,"|");if(-1===r)return[e.trim(),[]];let i=e.slice(r+1).trim(),s=n.get(i);return void 0===s&&(s=function(e,t,n){let r=n??e.join("|");return e.map(e=>{let n=j(e,"("),i=(e=>I(e,")").pop()??-1)(e);if(-1===i&&(i=e.lastIndexOf(")")),-1!==n&&-1===i&&_(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,...M(e.substring(n+1,i))}})}(R(i,"|").map(L),t,e),n.set(i,s)),[e.slice(0,r).trim(),s]}var W=new Map;function z(e){_(1101,[e])}function U(e){let[t,n]=H(e,"output",W);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("**")&&z(e);let t=e.split(".").length;t>512&&_(117,[e,t])}(r),{Ze:r,et:n}}var D=[["$watch","temporal"],["$stream","temporal"],["$listKeys","list-keys"],["$recursion","recursion"]],F=["enableMustache","sameValueGuard","enableDirectionalInitialSync"];function q(e){return e.includes("**")&&z(e),e}var B=0;function G(e,t,n){let r=e.get(t);return void 0===r&&e.set(t,r=n()),r}var K=()=>new Set,V=()=>[];function J(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}function Q(e,t){return e===t||e!=e&&t!=t}function X(e,t,n){let r=e._?.get(t);void 0!==r&&r.delete(n)&&0===r.size&&e._.delete(t)}function Y(e,t){for(let n=0;n<t.length;n++){if(null==e)return;e=e[t[n]]}return e}function Z(e,t){for(;null!==e&&e.l.n>t;)e=e.l.ae;return null!==e&&e.l.n===t?e:null}function ee(e,t,n){let r=Z(e,n);return null!==r&&r.l.o===t.h[n]?r:null}var te=class{constructor(e,t){this.je=0,this.u=null,this.Le=0,this.bt=new Set,this.tt=new Map,this.Un=Symbol("wcs.block"),this.element=null,this.vt=[],this.Be=null,this.qn=[],this.Ht=0,this.X=null,this.oe=new Map,this.ce=new Map,this.De=[],this.Me=[],this.We=[],this.kt=!1,this.hn=!1,this.Ut=new WeakMap,this.j=0,this.qt=0,this.gn=!1,this.Kt=!1,this.zt=!1,this.Te=0,this.Kn=()=>{this.j=0,this.gn=!1},this.zn=()=>{this.Te--},this.rp=null,this.rr=null,this.Mo=()=>this.Xt(),this.Wo=(e,t)=>e(this.proxy,...t),this.Xn=[],this.nt=[],this._o={$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=Z(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.Ie??(r.Ie=[]);if(!n.some(n=>n.getter===e&&n.Yn===t)){n.push({getter:e,Yn:t});let i=e.h[t];(i.Ct??(i.Ct=[])).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,Z(this.u,n.n)))},$dependOn:e=>{this.resolve(q(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=q(e[0]),n=e[1]??[],r=this.o(t,!0);this.wn("$resolve",t,r,n,!0);let i=this.Qn(r,n,null);if(e.length<3)return this.read(r,i);this.T(r,i,e[2])},$postUpdate:e=>{this.resolve(q(e),this.u);let t=this.rp,n=this.rr;"*"===t.s&&null!==n&&(n.R=n.l.C[n.b],this.P.Yt(n)),this.bn(t,n),null!==n&&this.Jn(n,t,void 0,n.R,!1),0===t.n&&this.Zn(t,void 0,void 0,!0),this.Gt(t,n,void 0,void 0,!1)}},this.P=t,this.I=new i(e=>{this.nt.push(e),this.ot(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.rt(t);if(t.indexOf(".")<0){let e=n.I.jt(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(q(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.je++)}for(let e of this.I.all())this.ot(e)}ot(e){e.t.includes("**")&&z(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(P.test(n))e.getter=function(){return this[n]};else{let r=t.split("."),i=r.findIndex((e,t)=>t>0&&e.charCodeAt(0)>=48&&e.charCodeAt(0)<=57);if(i<0||r.indexOf("*",i)>=0)return;e.getter=()=>(this.resolve(t,this.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.Wn=!0,e.n>0&&(e.A=this.je++)}_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.Qt(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.Dt(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.Dt(t);else n.Dt(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=G(this.Ut,t,V);if(n.push(e),n.length>1)for(let e of n)e.yt=!0}c.Jt?.(this,e,n),(null!==e.$||null!==e.D)&&!e.te&&(e.te=!0,this.Me.push(e),this.we());let r=e.o.Ct;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)}Dt(e){e.y=!1;let t=e._;if(null!==t){for(let e of t)X(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.Dt(e)}}oo(e){let t=this.Ut.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?ee(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.h[o],c=this._e(i,a),h=t[l++];if(h<0)h=ee(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}it(e,t){return 0===e.n?Y(this.target,e.K):null===t?void 0:Y(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.it(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._n(r),0===r.n?e.Z!==n.ue&&(e.Z=n.ue,n.kn.push(e)):e.n>0&&Z(t,Math.min(e.n,r.n))!==Z(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.Ht;n++){let r=this.qn[n];r.getter===e&&r.r===t&&_(701,[e.t])}this.Ht>=128&&_(801,[e.t]);let n=this.Ht++;this.Le++;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=++B,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.Le--,this.Ht--,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.J=e.J.filter(t=>t.Z===n||t.n>0||!t.se&&Array.isArray(null!==t.getter?t.z:this.it(t,null))||this.io(t,e))}io(e,t){return e.Io(t),this.nt.push(e),!1}zo(){for(let e=this.nt;e.length>0;e=this.nt){this.nt=[];let t=new Set;for(let n of e)if(!(n.pn||n.mn||null===n.d||n.c.length>0||n.W.length>0)&&(null===n.getter||n.Wn&&n.A<0)&&null===n._){n.mn=!0,this.I.Lt(n),t.add(n.d);for(let e of n.J)this.io(e,n)}for(let e of t)(e.c=e.c.filter(e=>!e.mn)).length||this.nt.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.It??(r.It=[]);e.includes(n)||e.push(n)}}}rt(e){let t=e.charCodeAt(1);if(t>=48&&t<=57){let n=2===e.length?t-48:P.test(e)?+e.slice(1):0;return(n<1||n>128)&&_(1001,[e]),this.watchIndex(n),Z(this.u,n)?.b}let n=this._o[e];if(void 0!==n)return n;switch(e){case"$stateElement":return this.element;case"$command":return this.commands}return c.rt?.(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 Q(this.read(n,r),t);let i=this.X;return null!==i&&0===i.ye&&this.Xo(n,t,i),Q(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(Q(o.key,t))return void(o.ue=n.ue);o.ue!==n.ue&&(X(e,o.key,o.sub),s.splice(i--,1))}}let o={getter:r,r:i};G(e._??=new Map,t,K).add(o),s.push({source:e,key:t,sub:o,ue:n.ue})}Zn(e,t,n,r){this.Zt(e,i=>{let s=i._;if(null===s&&null===i.Ie)return;let o=i===e?[]:i.t.slice(e.t.length+1).split("."),l=Y(t,o),a=Y(n,o);if(null!==i.Ie&&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.be(this,n.getter,n.r):X(i,e,n)}})}T(e,t,n,r=!1,i=!1){if(this.Le>0&&_(8),i||this.Te>0?this.Kt=!0:this.zt=!0,c.Ae?.(this,e,t,n,i))return;if(null!==e.ie){try{this.Sn(e.ie,t,[n])}finally{this.Gt(e,t,void 0,void 0,!1,i)}return}null!==e.getter&&_(2,[e.t]),e.n>0&&null===t&&_(3,[e.t]);let s=e.se?this.v(e,t):this.it(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.Yt(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.Jn(t,e,s,n),0===e.n&&this.Zn(e,s,n),this.Gt(e,t,s,n,!0,i)}}so(e){return(this.Ut.get(e.C)??[]).filter(t=>t.C===e.C&&(null===t.ae||t.ae.y))}Jn(e,t,r,i,s=!0){let o=e.l;if(!o.yt&&null===o.o.getter&&!o.o.W.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.Yt(n)),s?this.En(o,n):this.bn(o,n),this.Gt(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.Ut.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.W)&&c.add(r.W)&&(!i&&t!==e&&this.P.be(this,r,null),d(t,r.W))}},f=e=>{for(let t of e.J)if(!c.has(t)&&c.add(t))if(null!==t.getter)f(t);else if(!t.se){let e=this.it(t,null);h(e)&&d(e,t.W)}};null!==o.o.getter?f(o.o):d(o.C,o.o.W)}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.Ie)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.be(this,e,t):this.en(t,e,t=>this.P.be(this,e,t))}Gt(e,t,n,r,i,s){c.ve?.(this,e,t,n,r,i,s),this.Ve(e,t)}Ve(e,t){this.P.Qo(this,e,t),this.we()}ao(e){let t=this.tt.get(e);if(void 0!==t)return t;let n=Symbol(`wcs.on${e}`);this.tt.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.Jo(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.tn(t);for(let e of this.oe.values())this.co(e);this.Be=null;try{this.Xt()}finally{this.$n()}c.element?.(this,"reset")}eo(e){for(let[t,n]of D)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)(!F.includes(e)||"boolean"!=typeof n[e])&&_(44,["$behavior",e]);let[r,i,s]=F.map(e=>n[e]??!0);void 0!==this.target&&(r!==this.Wt||i!==this._t||s!==this.Vt)&&_(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.Wo);this.Wt=r,this._t=i,this.Vt=s,c.de?.(this,e),this.target=e,this.je=0;for(let e of this.I.all())e.jo();this.Xn.length=0,this.to(e),this.commands=o,this.Pe=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.Pe.get(e);void 0===r&&_(1301,[e],e,this.Pe.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.Bt&&t.o.ee(e)&&(t.Bt=!0,this.We.push(t))}if(null===t)return void this.Zt(e,e=>{let t=this.ce.get(e);if(void 0!==t)for(let e of t)this.tn(e)});let n=t.he;if(null!==n)for(let t=0;t<n.length;t++)n[t].o.ee(e)&&this.tn(n[t]);let r=t.$;null!==r&&null!==r.fe&&r.uo(this,e);let i=t.l.D;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.Zt(e,e=>{let r=e.W;for(let i=0;i<r.length;i++){let s=r[i];if(0===s.n)this.st(s,null,n);else if(null===t||0===e.n||s.h[1]!==e.h[1]||null!==s.ft&&s.ft.has(e))this.nn(s.h[s.n],e=>this.st(s,e,n));else if(s.n<=e.n){let e=Z(t,s.n);null!==e&&this.st(s,e,n)}else this.en(t,s,e=>this.st(s,e,n))}})}st(e,t,n){n(e,t)&&(c.ke?.(this,e,t),this.St(e,t),this.Nn(e,t,n))}Zt(e,t){t(e);let n=e.c;for(let e=0;e<n.length;e++)this.Zt(n[e],t)}nn(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.nn(e.h[e.n],n=>{let r=n.c?.get(e);void 0!==r&&t(r)})}en(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.en(e,t,n)}nr(e){let t=e.r;null===t?G(this.ce,e.o,K).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)}tn(e){e.te||(e.te=!0,this.De.push(e),this.we())}we(){this.kt||(this.kt=!0,queueMicrotask(this.Mo))}Rn(){for(let e of this.De)e.te=!1;for(let e of this.Me)e.te=!1;for(let e of this.We)e.Bt=!1;this.De=[],this.Me=[],this.We=[],this.P.bt(this)}fo(e,t){let n=[...new Set([...this.De,...this.Me,...this.We].map(e=>e.o.t))];console.error(`[@wcstack/state] ${w(e)}`,n),c.at?.(this,{type:"state:render-chain-limit",maxDepth:t,paths:n}),this.Rn()}Xt(){this.kt=!1;let e=this.qt;this.qt=0;let t=0;if(!this.Kt||this.zt?this.Kn():e>0?t=e:1===(t=++this.j)&&setTimeout(this.Kn,0),this.Kt=this.zt=!1,t>100)101===t?this.fo(41,100):this.Rn();else{this.hn=!0;try{for(let e=0;this.De.length>0||this.Me.length>0||this.We.length>0;e++){if(e>=32){this.gn?this.Rn():this.fo(11,32),this.gn=!0;break}let n=this.We;if(n.length>0){this.We=[];for(let e of n)e.Bt=!1,this.no(e)}let r=this.Me,i=this.De;this.Me=[],this.De=[];let s=()=>{for(let e of r){e.te=!1;for(let t of[e.$,...e.D??[]])if(null!==t&&t.y)try{t.Et()}catch(n){this.Qt(n,e.o.t,t.S,"for")}}for(let e=0;e<2;e++)for(let t=0;t<i.length;t++){let n=i[t];!n.te||null===n.j==(0===e)||(n.te=!1,(null===n.Pn||n.Pn.y)&&this.He(n))}this.hn||(this.Ue(),this.kt&&(this.qt=t+1))},o=r.length>0||i.some(e=>null!==e.j)?C("state",s):s();void 0!==o&&o.then(void 0,e=>console.error(e))}}finally{this.hn=!1}this.Kt=this.zt=!1,this.Ue(),c.Fe?.(this),this.zo(),e>0&&this.kt&&(this.qt=t+1)}}$t(e,t){this.vt.push([e,t])}Qt(e,t,n,r){this.$t(e,{o:{t:t},a:n,on:()=>r})}He(e){try{e.apply()}catch(t){return void this.vt.push([t,e])}null!==this.Be&&this.po(e.o,e.r)}po(e,t){let n=G(this.Be,e.t,V);null!==t&&n.push(this.H(t))}$n(){this.Be="function"==typeof this.target.$renderedCallback?new Map:null}Ue(){let e=this.Be;if(null!==e&&e.size>0){this.Be=new Map;let t,n=[...e.keys()],r={};for(let[t,n]of e)n.length>0&&(r[t]=n);this.Te++;try{t=this.Se("$renderedCallback",[n,r])}catch(e){console.error(e)}J(t)?t.then(this.zn,e=>{this.zn(),console.error(e)}):this.Te--}if(0===this.vt.length)return;let t=this.vt;this.vt=[];let n=this.target.$errorCallback;for(let[r,i]of t){c.qe?.(this,r,i);let t=i.o.t,s=i.on();if("function"==typeof n)try{let e=this.Se("$errorCallback",[r,{path:t,bindingType:s,node:i.a}]);J(e)&&e.then(void 0,e=>console.error(e))}catch(e){console.error(e)}else console.error(`[@wcstack/state] ${w(12,[s,t])}`,r)}}Se(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=ee(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.Le>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])}},ne={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"},re=new Map,ie=new Set(["if","elseif","else","for"]),se=new Set([E,"if","elseif","for","..."]),oe=new Set([x,T,"style","command",A,"state"]);function le(e){let t=function(e){return R(e,";")}(e).map(L).filter(e=>e.length>0).map(e=>{let t=j(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(se.has(i)){let t;return i!==n&&_(102,[e,i]),i===E?(r.length>0&&_(103,[e]),t={Ze:"#else",et:[]}):"..."===i?(0===r.length&&_(104,[e]),t=U(r),t.et.length>0&&_(105,[e])):(t=U(r),"for"===i&&t.et.length>0&&_(121,[e])),{Ee:i,$e:[i],rn:[],L:[],...t,w:"..."===i?"spread":i}}(i===x||i===T)&&_(122,[e,i]);let s=U(r),o=function(e){let[t,n]=H(e,"input",re),r=t.split("#").map(L);r.length>2&&_(115,[t]);let[i,s]=r,o=i.split(".").map(L);return!(o.length>1&&""===o[0])&&(0===i.length||o.some(e=>0===e.length))&&_(116,[e]),{Ee:i,$e:o,rn:s?s.split(",").map(L):[],L:n}}(n),[l]=o.$e;if(""===l&&o.$e.length>1){let e=o.$e.slice(1);return(e.includes("")||oe.has(e[0]))&&_(106,[n]),{...o,Ee:e.join("."),$e:e,...s,w:"prop"}}return{...o,...s,w:"radio"===i||"checkbox"===i?i:l===A||l.startsWith("on")?"event":"prop"}});return t.length>1&&t.some(e=>ie.has(e.w))&&_(201,[e]),t}var ae=["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"],ue=new Map,ce=new Map;function he(e){for(let t of Object.keys(e))ue.set(t,{...e[t]});ce.clear()}function de(e){return ue.has(e)}function fe(e){_(26,[e])}function pe(e){_(27,[e])}function me(e){_(28,[e])}function ge(e){_(29,[e])}function ye(e){return!(!e||isNaN(Number(e)))}function be(e,t){return ye(e)||pe(t),Number(e)}function ve(e,t,n){return be(e?.[t]??fe(n),n)}function we(e,t){return void 0!==t&&t.length>0?t[0]:e}var _e=(e,t)=>({factory:n=>{let r=ve(n,0,e);return n=>("number"!=typeof n&&me(e),t(n,r))},arity:[1,1]}),$e={eq:{factory:(e,t)=>{let n=e?.[0]??fe("eq"),r=we(n,t);return e=>"number"==typeof e?"string"!=typeof r?e===r:(ye(n)||pe("eq"),e===Number(n)):"string"==typeof e?e===n:e===r},arity:[1,1]},ne:{factory:(e,t)=>{let n=e?.[0]??fe("ne"),r=we(n,t);return e=>"number"==typeof e?"string"!=typeof r?e!==r:(ye(n)||pe("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==r},arity:[1,1]},not:{factory:()=>e=>!e,arity:[0,0]},lt:_e("lt",(e,t)=>e<t),le:_e("le",(e,t)=>e<=t),gt:_e("gt",(e,t)=>e>t),ge:_e("ge",(e,t)=>e>=t),falsy:{factory:()=>e=>!e,arity:[0,0]},truthy:{factory:()=>e=>!!e,arity:[0,0]},boolean:{factory:()=>e=>!!e,arity:[0,0]}},ke=!1;function Se(e,t){if(null!==e)for(let n=0;n<e.length;n++)t=e[n](t);return t}function Ne(e){return 0===e.length?null:(ke||(ke=!0,he($e)),e.map(e=>function(e,t,n){let r=`${e}${function(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}(t,n)}`,i=ce.get(r);if(typeof i<"u")return i;let s=ue.get(e);void 0===s&&function(e,t){ae.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,ue.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 ce.set(r,a),a}(e.Hn,e.args,e.literals)))}var Ce=Symbol.for("wcstack.trustedTypes.policy");function Ee(){let e=globalThis[Ce];return null!==e&&"object"==typeof e?e:null}function Ae(e){return"innerHTML"===e||"outerHTML"===e||"srcdoc"===e}function xe(e){if(globalThis.trustedTypes?.isHTML(e))return e;let t=null==e?"":String(e),n=Ee(),r=n?.createHTML;return"function"==typeof r?r.call(n,t):t}var Te=Symbol.for("wcstack.state.view-transition-naming"),Pe=new WeakSet;function Oe(){let e=N("state");return null!==e&&"auto"===e.naming?e.namingLimit:-1}var Me=new WeakMap,Le=e=>e.customElementRegistry??customElements;function Ie(e,t,n,r,i,s=!1){let o=n.localName;if(!o.includes("-"))return i(null);let l=Le(n);if(!s&&!n.isConnected&&void 0===l.get(o)&&"customElementRegistry"in n)return void queueMicrotask(()=>Ie(e,t,n,r,i,!0));let a=()=>{let e=l.get(o);l.upgrade(n),i(e?function(e){if(Me.has(e))return Me.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 Set,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.add(e.name);for(let e of t.commands??[])null!==e&&"object"==typeof e&&"string"==typeof e.name&&n.commands.add(e.name)}return Me.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){Ue(e,r,t,n)}e.we()})}function je(e,t,n,r,i=t.o,s,o,l){let a=l.properties.get(r)??null,u=l.inputs.has(r),h=e.Vt;h&&null===a&&!u&&_(38,[r]);let d=t.U;(null===a?"element"===d||"auto"===d:!u&&("state"===d||"auto"===d))&&_(39,[d,r]),"connect"===t.Y&&null===a&&_(40,[r]);let f=h&&null!==a&&!u,p=new qe(e,We,n,r,i,s,o,t.N,void 0);p.L=t.L,Ye(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=Se(p.L,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.He(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.He(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 Re(e,t,n){_(e,[t.localName,n])}var He=new Set(["click","dblclick","input","change","submit","keydown","keyup","mousedown","mouseup","pointerdown","pointerup"]),We=11,ze=["text","prop","prop","prop","prop","event","for","if","prop","radio","checkbox","prop","prop","event","spread"],Ue=(e,t,n,r)=>e.Qt(t,n.o?.t??n.xt,r,ze[n.i]),De=Symbol();function Fe(e,t,n){let r=t.U;return null===r||"state"===r||"auto"===r&&void 0!==e.v(t.o,n)?t.q:De}var qe=class{constructor(e,t,n,r,i,s,o,l,a,u=null){this.te=!1,this.L=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.j=u}on(){return ze[this.i]}apply(){if(null!==this.j)return void this.j.Et();let e=Se(this.N,this.engine.read(this.o,this.r));if(e===this.value&&9!==this.i&&("object"!=typeof e||null===e||this.i===We||8===this.i||Ae(this.name)))return;if(this.value===De)return void(this.value=e);let t=this.a;if(this.i!==We)9===this.i?t.checked=void 0!==e&&this.sn()===e:10===this.i?t.checked=Array.isArray(e)&&e.includes(this.sn()):Ge(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}}}sn(){return Se(this.L,this.a.value)}ir(){let e,t=this.a,n=this.engine;if(9===this.i){if(!t.checked)return;e=this.sn()}else if(10===this.i){let r=this.sn(),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=Se(this.L,t[this.name]),this.value=NaN;n.T(this.o,this.r,e,!1,!0)}},Be=e=>"textContent"===e||"innerText"===e||"innerHTML"===e;function Ge(e,t,n,r){switch(e){case 0:return void(t.data=null==r?"":String(r));case 1:return void(Be(n)?t[n]="innerHTML"===n?xe(r):null==r?"":String(r):Ae(n)?null==r&&"srcdoc"===n?t.removeAttribute(n):void 0!==r&&(t[n]=xe(r)):void 0!==r&&(t[n]!==r&&!("value"===n&&t.value===String(r))&&(t[n]=r),("value"===n||"selectedIndex"===n)&&"select"===t.localName&&(t[Ke]=[n,r])));case 8:return void(t.innerHTML=xe(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 Ke=Symbol();function Ve(e){let t="optgroup"===e.localName?e.parentNode:e,n=t?.[Ke];void 0!==n&&(t[n[0]]=n[1])}var Je=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.Ke=t,this.B=n,this.F=r}Jo(e,t){let n=t.target,r=this.F,i=[],s=null;for(let t of r.Pe){if(t.name!==e)continue;let o=r.On[t.a],l=lt(null===this.B?this.Ke:this.B[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.B?this.Ke:this.B[this.B.length-1]}ze(){let e=this.Fn;return(null===e?null:e.Cn(this.Ke))??this.Ke}insertBefore(e,t){let n=this.s;for(let r=this.ze();;){let i=r.nextSibling;if(e.insertBefore(r,t),r===n)return;r=i}}wo(){null===this.B?this.Ke.remove():at(this.ze(),this.s)}xe(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.xe()}},Qe=class extends Je{constructor(e,t,n,r){super(e,t,n,r),this.bo=0,this.V=null,this.fe=0===r.Xe.length?null:new Array(2*r.Xe.length)}vo(e,t){let n=this.V??=new Array(this.F.Xe.length),r=n[t];if(void 0===r){let i=this.F.Xe[t],s=this.fe;r=n[t]=new qe(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.Xe;for(let r=0;r<n.length;r++)n[r].o.ee(t)&&e.tn(this.vo(e,r))}xe(e){let t=this.r;t.$===this&&(t.$=null),super.xe(e)}};function Xe(e,t,n,r){let i=Z(n,t.n);try{return e._e(i,t)}catch(n){return e.Qt(n,t.t,r,"for"),null===i?e.oe.get(t):i.c.get(t)}}function Ye(e,t,n){n&&e.nr(t);let r=t.Pn;null!==r&&(r.he??=[]).push(t)}var Ze=null;function et(){let e=Ze;return Ze=null,e}var tt=-1;function nt(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.ln).cloneNode(!0);if(!h)for(let e=0;e<l.length;e++){let t=l[e];a[t]=lt(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 Qe(n,s,u,t),null===r.map?n.$=m:r.map.set(n,m)):p=new Je(n,s,u,t),tt>=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||Pe.has(i))return;let o=globalThis[Te]??={counter:0,assigned:0,warned:!1};o.assigned>=r?o.warned||(o.warned=!0,console.warn(`[@wcstack/state] ${w(25,[r])}`)):(Pe.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",tt),t.Pe.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.Be,b=t.lr?a.slice(0,o.length):a,v=null===m?null:m.fe;if(null!==v){let e=t.Xe;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.He(r);continue}try{let t=Se(i.N,e.read(i.o,n));t!==i.q&&(Ge(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 ot(e,i.F,Xe(e,i.o,n,o),o);(p.c??=[]).push(t),o===s&&(p.Fn=t),t.Et();break}case 7:{let t=it(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{rt(e,i,o,n,p)}catch(t){Ue(e,t,i,o)}}}return Ze=p,f}function rt(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.tt){let r=e.ao(n.name),i=t[r];t[r]=void 0===i?o:e=>{i(e),o(e)},n.Ne&&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 Ie(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&&Re(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 Ie(e,t,s,i,n=>function(e,t,n,r,i){let s=t.name;null===i&&Re(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=Z(r,o.n);if(14===t.i)return void Ie(e,t,s,i,n=>function(e,t,n,r,i,s){null===s&&Re(1501,n,`"...: ${t.o.t}"`);let o=new Set([...s.properties.keys(),...s.inputs]);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;je(e,{...t,U:null,Y:null},n,l,o,a,i,s)}}(e,t,s,l,i,n));if(t.Ne&&1===t.i)return void Ie(e,t,s,i,n=>function(e,t,n,r,i,s){if(null!==s)return void je(e,t,n,t.name,t.o,r,i,s);let o=new qe(e,1,n,t.name,t.o,r,i,t.N,Fe(e,t,r));o.L=t.L,!c.ar?.(o,t.ro)&&(Ye(e,o,!0),e.He(o))}(e,t,s,l,i,n));let a=new qe(e,t.i,n,t.name,o,l,i,t.N,Fe(e,t,l));a.L=t.L,Ye(e,a,!0),e.He(a),null!==t.Tt&&n.addEventListener(t.Tt,()=>a.ir())}function it(e,t,n,r){let i=new st(e,t,n),s=null;for(let o of t){if(null===o.o)continue;let t=o.o,l=new qe(e,7,o.S,"if",t,Z(n,t.n),r,null,void 0,i);Ye(e,l,!0),null===r&&i.ce.push(l),s??=l}return e.He(s),i}var st=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.ze():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||Se(r.N,e.read(r.o,Z(this.r,r.o.n)))){t=n;break}}if(t!==this.b&&(tt=Oe(),null!==this.O&&(this.O.wo(),this.O.xe(e),this.O=null),this.b=t,t>=0)){let n=this.G[t],r=nt(e,n.F,this.r,null,n.S);this.O=et();let i=n.S.parentNode;i.insertBefore(r,n.S),Ve(i)}}xe(){this.y=!1;for(let e of this.ce)this.engine.xn(e);null!==this.O&&this.O.xe(this.engine)}},ot=class{constructor(e,t,n,r){this.y=!0,this.Re=[],this.engine=e,this.F=t,this.l=n,this.S=r,null===n.$?(n.$=this,this.map=null):((n.D??=[]).push(this),this.map=new Map)}Cn(e){return 0===this.Re.length?null:this.Re[0].ze()}At(e){return null===this.map?e.$:this.map.get(e)??null}Lt(e){let t=this.map;null!==t&&t.get(e.r)===e&&t.delete(e.r),e.xe(this.engine)}Et(){let e=this.engine,t=this.l.f,n=this.Re;tt=Oe();let r=t.length,i=n.length,s=this.S,o=s.parentNode;if(0===r){if(i>0){let e=n[0].ze(),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):at(e,t);for(let e=0;e<i;e++)this.Lt(n[e])}return void(this.Re=[])}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.Lt(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].ze():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(nt(e,this.F,n,this),i),u=et()),l[a+s]=u,i=u.ze()}}else{let n=document.createDocumentFragment();for(let r=a;r<=c;r++)n.appendChild(nt(e,this.F,t[r],this)),l[r]=et();o.insertBefore(n,d)}}this.Re=l,Ve(o)}xe(){this.y=!1;let e=this.l;if(e.$===this)e.$=null;else if(null!==e.D){let t=e.D.indexOf(this);t>=0&&e.D.splice(t,1),0===e.D.length&&(e.D=null)}for(let e of this.Re)e.xe(this.engine);this.map?.clear()}};function lt(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 at(e,t){for(let n,r=e;r!==t;r=n)n=r.nextSibling,r.remove();t.remove()}var ut=()=>ne.bindAttributeName;function ct(){return{a:0,i:1,name:"",o:null,N:null,q:t,An:null,F:null,G:null,L:null,Tt:null,Ne:!1,U:null,Y:null,ro:!1,Rt:!1,Pt:!1,xt:null,go:null,A:-1,tt:!1,yo:!1}}var ht=["state","element","auto","none"],dt=["call","connect"],ft="$command.";function pt(e,t,n){P.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 mt=e=>1===e.i&&("outerHTML"===e.name||"outerText"===e.name),gt=e=>8===e.i||mt(e)||1===e.i&&Be(e.name);function yt(e){_(202,[e])}function bt(e,t,n,r,i){let s=le(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.Vt||_(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?ht:dt).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.rn),o=r.localName.includes("-"),l=t.$e,a=t.Ze;if("event"===t.w){if(null!==s.U&&"none"!==s.U&&_(36),"eventToken"===l[0])return{...ct(),a:i,i:13,name:l.slice(1).join("."),xt:a,Ne:o,Rt:s.Rt,Pt:s.Pt};let n=a.startsWith(ft)?a.slice(9):null,{Rt:r,Pt:u}=s,c=t.Ee.slice(2),h=t.rn.includes("direct"),d=!h&&He.has(c);return d&&e.ao(c),{...ct(),a:i,i:5,name:c,tt:d,Ne: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);J(n)&&n.then(void 0,e=>console.error(e))}}catch(e){console.error(e)}}}}if("spread"===t.w)return{...ct(),a:i,i:14,o:pt(e,a,n),Ne:o};if("command"===l[0]&&l.length>1)return a.startsWith(ft)||_(1201,[t.Ee,a]),{...ct(),a:i,i:12,name:l.slice(1).join("."),xt:a,Ne:o};let u=pt(e,a,n),c={...ct(),a:i,i:1,name:t.Ee,o:u,N:Ne(t.et),L:Ne(t.L),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.Ee?(c.i=8,c):(c.name="text"===t.Ee?"textContent":t.Ee,c.Ne=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 vt=/\{\{([\s\S]+?)\}\}/g;function wt(e){let t=e.data,n=[],r=0;vt.lastIndex=0;for(let i=vt.exec(t);null!==i;i=vt.exec(t)){let s=vt.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=vt.lastIndex}return 0===n.length||(r<t.length&&e.before(t.slice(r)),e.remove()),n}function _t(e,t,n,r){let i=function(e){return{Ee:"textContent",$e:["textContent"],rn:[],L:[],...U(e),w:"text"}}(t);return{...ct(),a:r,i:0,o:pt(e,i.Ze,n),N:Ne(i.et),q:""}}function $t(e){let t=e.getAttribute(ut());if(null===t)return null;let n=le(t)[0];return void 0===n||"for"!==n.w&&"if"!==n.w&&"elseif"!==n.w&&"else"!==n.w?null:n}var kt=(e,t)=>0===e?ne.commentIfPrefix:null===t.o?ne.commentElsePrefix:ne.commentElseIfPrefix;function St(e,t,n){let r=(t,r)=>({el:t,o:"else"===r.w?null:pt(e,r.Ze,n),N:"else"===r.w?null:Ne(r.et)}),i=[r(t,$t(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=$t(e);if(null===t||"elseif"!==t.w&&"else"!==t.w||(i.push(r(e,t)),"else"===t.w))break}return i}var Nt=new WeakSet;function Ct(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||Nt.has(t))continue;if(Nt.add(t),l===ne.tagNames.state){u([...t.childNodes]);continue}}let h="template"===l?$t(t):null;if(null!==h){if("for"===h.w){let r=pt(e,h.Ze,n),s=xt(e,t,r,!0);i(a(t,ne.commentForPrefix),r,s)}else"if"===h.w?s(St(e,t,n).map((t,r)=>({F:xt(e,t.el,n,!1),o:t.o,N:t.N,S:a(t.el,kt(r,t))}))):yt(h.w);continue}let f=t.getAttribute(ut()),p=null===f?null:bt(e,f,n,t,0),m="noscript"!==l&&"iframe"!==l&&!p?.some(gt)&&!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.Wt&&d.data.includes("{{")&&!Nt.has(d))for(let{a:e,cr:t}of wt(d))l(e,t);else if(8===d.nodeType){let e=Et.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 Et=/^\s*@@\s*(?:wcs-text)?\s*:\s*([\s\S]+?)\s*$/,At=e=>{let t=document.createRange();return t.selectNodeContents(e),e.content??t.cloneContents()};function xt(e,t,n,r){let i=document.importNode(At(t),!0),s=[],o=[],l=e=>s.push(e)-1;Ct(e,[...i.childNodes],n,!1,(e,t,n)=>{o.push({...ct(),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({...ct(),a:t[0].a,i:7,G:t})},(e,t)=>{let n=l(e);for(let e of t)mt(e)&&_(203,[e.name]),e.a=n;o.push(...t),e.removeAttribute(ut())},(t,r)=>{o.push(_t(e,r,n,l(t)))}),Mt(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.tt&&!e.Ne&&!Tt(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&&Pt(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{ln:i,root:u?i.firstChild:null,On:a,build:g,Pe:f,sr:p,In:u,lr:c,ko:[],Xe:h}}function Tt(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 Pt(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.Ne&&null===e.Tt;default:return!1}}var Ot=new Set(["table","thead","tbody","tfoot","tr","colgroup","select","optgroup","datalist"]);function Mt(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&&Mt(r,t,Ot.has(r.localName)),r=e}}var Lt=new WeakMap;function It(e,t){let n=9===t.nodeType?t.body:t;e.root=t,Lt.set(t,e),Rt(e,[...n.childNodes]),e.Ue()}function jt(e,t,n){try{let r="template"===t.localName?$t(t):null;null!==r&&!n&&_(204,[r.w]),Rt(e,[t])}catch(e){console.error(e)}e.Ue()}function Rt(e,t){Ct(e,t,null,!0,(t,n,r)=>{new ot(e,r,Xe(e,n,null,t),t).Et()},t=>{it(e,t,null,null)},(t,n)=>{c.jn?.(e,t,n);for(let r of n)rt(e,r,t,null,null)},(t,n)=>{c.jn?.(e,t,n),rt(e,_t(e,n,null,0),t,null,null)})}var Ht=Symbol.for("wcstack.binder"),Wt=Symbol.for("wcstack.binder.pending"),zt=Symbol.for("wcstack.binder.taken"),Ut=new Map;function Dt(e,t){if(1!==e.nodeType||!e.isConnected)return;let n=Lt.get(e.getRootNode());void 0===n||!1===n.element?.isConnected?Ut.set(e,t):jt(n,e,t?.range)}function Ft(){let e=[...Ut];Ut.clear();for(let[t,n]of e)Dt(t,n);!function(){let e=function(){let e=globalThis[Ht];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[Wt];return void 0===t&&(t=[],e[Wt]=t),t}();if(0===t.length)return;let n=t.splice(0,t.length),r=function(){let e=globalThis,t=e[zt];return void 0===t&&(t=new WeakSet,e[zt]=t),t}();for(let t of n)r.add(t),e.bind(t)}()}var qt=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)}}Qo(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.It;if(null!==n)for(let r of n)r.n===t.l.n?e.st(r,t,this.Z):e.en(t,r,t=>e.st(r,t,this.Z))}be(e,t,n){this.Z(t,n),c.ke?.(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.je).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}}Yt(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.nn(t.h[t.n],e=>{let i=e.ht;null!==i&&i[t.A]===n&&(i[t.A]=r)}))}},Bt=0,Gt=new WeakMap;function Kt(e,t=e.getRootNode()){Gt.set(t,[...Gt.get(t)??[],e].filter((e,t,n)=>e.isConnected&&n.lastIndexOf(e)===t))}function Vt(e){let t=Gt.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?Gt.get(e)!==t?Vt(e):Promise.reject(r.errors[0]):void 0)}var Jt=typeof HTMLElement>"u"?class{}:HTMLElement,Qt=class extends Jt{constructor(){super(),this.engine=null,this.Ln=!1,this.qe=!1,this.q=null,this.Ye=null,this.loaded=!1,this.un=null,this.connectedCallbackPromise=new Promise((e,t)=>{this.cn=e,this.$o=t}),this.connectedCallbackPromise.catch(()=>{}),this.initializePromise=new Promise(e=>{this.an=e})}static{this.getBindingsReady=Vt}static{this.hasConnectedCallbackPromise=!0}connectedCallback(){if(this.Ln){if(null!==this.Ye)return void this.Ye.Ge();Kt(this);let e=this.engine;if(null!==e){let t=e.root;t===this.getRootNode()&&!Lt.has(t)&&Lt.set(t,e),Ft(),c.element?.(e,"back"),this.No("$connectedCallback",50,()=>{this.isConnected&&c.element?.(e,"connected")})}return}this.Ln=!0;let e=this.getRootNode(),t=c.ct?.(this,e);if(t)return this.Ye=t,!t.xo&&this.parentNode instanceof ShadowRoot&&Kt(this),void(void 0===t.Mt?this.Ro():t.Mt()).then(e=>(this.loaded=!0,t.start(e,()=>this.Po()))).then(()=>{this.an(),this.cn()},e=>this.$t(e,t.xo));this.start(e),Kt(this)}disconnectedCallback(){if(null!==this.Ye)return void this.Ye.Bn();let e=this.engine;if(null===e)return;let t=e.root;Lt.get(t)===e&&Lt.delete(t),Kt(this,t),this.No("$disconnectedCallback",51),c.element?.(e,"disconnected")}setInitialState(e){if(this.qe&&_(14),this.loaded)this.Ye.reset(e);else if(null===this.engine)if(null!==this.un){let t=this.un;this.un=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.Le++;try{t(n.proxy)}finally{"readonly"===e&&n.Le--}}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//${++Bt}`);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.un=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=Lt.get(e)?.element;i?.isConnected&&(i.V||i.Ye)&&_(47);let s=new te(n,new qt);s.element=this,this.engine=s,c.element?.(s,"mounting"),It(s,e),Ft(),s.$n(),this.Po(),await s.Se("$connectedCallback"),this.isConnected&&c.element?.(s,"connected"),this.cn()}catch(e){this.qe=!this.V,this.$t(e)}}Po(){this.V=!0,this.an()}$t(e,t){this.Ue(this.V?50:49,e),this.an(),t?this.cn():this.$o(e)}Ue(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.Se(e))().then(n,e=>this.Ue(t,e))}},Xt=[];function Yt(){return(Xt=Xt.filter(e=>e.deref())).map(e=>e.deref())}var Zt,en=e=>t=>{let n=e(t);return e=>null==e?e:n(e)},tn="en";function nn(){if(ne.locale!==Zt){Zt=ne.locale;try{tn=Intl.getCanonicalLocales(Zt)[0]}catch{console.warn(`[@wcstack/state] ${w(48,[Zt])}`),tn="en"}}return tn}var{eq:rn,ne:sn,not:on,lt:ln,le:an,gt:un,ge:cn,falsy:hn,truthy:dn,boolean:fn}=$e,pn={toFixed:{factory:e=>{let t=be(e?.[0]??"0","toFixed");return e=>("number"!=typeof e&&me("toFixed"),e.toFixed(t))},arity:[0,1]},locale:{factory:e=>{let t=e?.[0];return e=>("number"!=typeof e&&me("locale"),e.toLocaleString(t??nn()))},arity:[0,1]},upper:{factory:en(()=>e=>String(e).toUpperCase()),arity:[0,0]},lower:{factory:en(()=>e=>String(e).toLowerCase()),arity:[0,0]},capitalize:{factory:en(()=>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:en(()=>e=>String(e).trim()),arity:[0,0]},slice:{factory:en(e=>{let t=[ve(e,0,"slice")],n=e?.[1];return typeof n<"u"&&t.push(be(n,"slice")),e=>String(e).slice(...t)}),arity:[1,2]},padStart:{factory:en(e=>{let t=ve(e,0,"padStart"),n=e?.[1]??"0";return e=>String(e).padStart(t,n)}),arity:[1,2]},padEnd:{factory:en(e=>{let t=ve(e,0,"padEnd"),n=e?.[1]??" ";return e=>String(e).padEnd(t,n)}),arity:[1,2]},repeat:{factory:en(e=>{let t=ve(e,0,"repeat");return e=>String(e).repeat(t)}),arity:[1,1]},reverse:{factory:en(()=>e=>String(e).split("").reverse().join("")),arity:[0,0]},truncate:{factory:en(e=>{let t=ve(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,be(e?.[0]??"0","round"));return e=>("number"!=typeof e&&me("round"),Math.round(e*t)/t)},arity:[0,1]},floor:{factory:e=>{let t=Math.pow(10,be(e?.[0]??"0","floor"));return e=>("number"!=typeof e&&me("floor"),Math.floor(e*t)/t)},arity:[0,1]},ceil:{factory:e=>{let t=Math.pow(10,be(e?.[0]??"0","ceil"));return e=>("number"!=typeof e&&me("ceil"),Math.ceil(e*t)/t)},arity:[0,1]},percent:{factory:e=>{let t=be(e?.[0]??"0","percent");return e=>("number"!=typeof e&&me("percent"),`${(100*e).toFixed(t)}%`)},arity:[0,1]},unit:{factory:en(e=>{let t=e?.[0]??fe("unit");return e=>String(e)+t}),arity:[1,1]},date:{factory:e=>{let t=e?.[0];return e=>(e instanceof Date||ge("date"),e.toLocaleDateString(t??nn()))},arity:[0,1]},time:{factory:e=>{let t=e?.[0];return e=>(e instanceof Date||ge("time"),e.toLocaleTimeString(t??nn()))},arity:[0,1]},datetime:{factory:e=>{let t=e?.[0];return e=>(e instanceof Date||ge("datetime"),e.toLocaleString(t??nn()))},arity:[0,1]},ymd:{factory:e=>{let t=e?.[0]??"-";return e=>{e instanceof Date||ge("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||ge("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:rn,ne:sn,not:on,lt:ln,le:an,gt:un,ge:cn,add:_e("add",(e,t)=>e+t),sub:_e("sub",(e,t)=>e-t),mul:_e("mul",(e,t)=>e*t),div:_e("div",(e,t)=>e/t),mod:_e("mod",(e,t)=>e%t),abs:{factory:()=>e=>("number"!=typeof e&&me("abs"),Math.abs(e)),arity:[0,0]},clamp:{factory:e=>{let t=ve(e,0,"clamp"),n=ve(e,1,"clamp");return e=>("number"!=typeof e&&me("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:hn,truthy:dn,defaults:{factory:(e,t)=>{let n=we(e?.[0]??fe("defaults"),t);return e=>e||n},arity:[1,1]},coalesce:{factory:(e,t)=>{let n=we(e?.[0]??fe("coalesce"),t);return e=>e??n},arity:[1,1]},boolean:fn,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]}},mn=!1,gn={name:"formats",install:function(){mn||(mn=!0,he(pn))}};function yn(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 bn(e,t){if(0===e.length)return"";let n=e.toLowerCase(),r=null,i=3;for(let e of t){let t=yn(n,e.toLowerCase(),2);t<i&&(r=e,i=t)}return null!==r?` Did you mean "${r}"?`:""}var vn=" Validate statically: npx @wcstack/lint <file>.",wn=["","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"],_n=e=>{let t=wn[e/100|0];return t?`[wcs/${t}] `:""},$n=["enableMustache","sameValueGuard","enableDirectionalInitialSync"],kn=(e,t)=>`<${e}${t.map((e,t)=>t%2?`="${e}"`:` ${e}`).join("")}>`,Sn="https://github.com/wcstack/wcstack/blob/main/docs/csp.md",Nn={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 ${Sn}`,43:e=>`Failed to evaluate the inline <script> of <wcs-state>: ${e}. If this page sets a Content-Security-Policy, see ${Sn}`,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&&$n.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)=>`${kn(e,t)} failed to initialize.`,50:(e,...t)=>`${kn(e,t)} $connectedCallback failed.`,51:(e,...t)=>`${kn(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>").`,122:(e,t)=>"class"===t?`"${e}": "class:" needs a class name — "class.NAME:" toggles one class (a bare "class:" would set an element property named "class", which does nothing). To set the whole class attribute, bind "className:".`:`"${e}": "attr:" needs an attribute name — "attr.NAME:" sets one attribute (a bare "attr:" would set an element property named "attr", which does nothing).`,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 Cn(e,t){let n=Nn[e];return void 0===n?`${_n(e)}#${e} ${t.join(" ")}`:_n(e)+n(...t)}var En=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.']],xn={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function Tn(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(xn,e)?xn[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?bn(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"].':ae.some(de)||(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&&En.has(s[1])&&!/ path segments — the limit is |inserted content was not rendered|formats add-on/.test(e)&&(r+=vn),r}var Pn=new WeakMap,On=new WeakMap,Mn=new WeakSet,Ln=new WeakSet;function In(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 jn(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 Rn(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!==In(e.target,t.t)?.get?t:e.I.jt(o(t.t).o)}(e,t);if(n.some(e=>null!=i(e)?.getter))return null;for(let t of n){if(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=In(r,t.s);if(void 0===n&&null===t.d&&e.bt.has(t.s))return null;if(void 0===n){let n=jn(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 Hn(e){Mn.has(e)||(Mn.add(e),setTimeout(()=>function(e){Mn.delete(e);let t=Pn.get(e);if(void 0===t)return;let n=On.get(e);void 0===n&&On.set(e,n=new Set);for(let[r,i]of t){if(n.has(r))continue;n.add(r);let t=Rn(e,r);if(null===t)continue;let s=[...e.root?.querySelectorAll(`${ne.tagNames.state}[mount]`)??[]].find(e=>!Ln.has(e)&&(r.t+".").startsWith(e.getAttribute("mount")+"."));if(void 0!==s){n.delete(r),s.initializePromise.then(()=>{Ln.add(s),Hn(e)});continue}let[l,a]=i?["watch-path-missing","$watch path"]:["binding-path-missing","Bound path"];c.at?.(e,{type:"state:path-unresolved",source:i?"watch":"binding",path:r.t,missingSegment:t.seg});let u=e.I.jt(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.${bn(t.seg,t.names)}${h} Updates to this path will be silently dropped.${vn}`)}}(e),0))}function Wn(e,t,n=!1){if("$"===t.t[0]||t.t.includes("#")||!n&&null===t.d)return;let r=Pn.get(e);void 0===r&&Pn.set(e,r=new Map),r.has(t)||r.set(t,n),Hn(e)}var zn=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Un=!1;function Dn(e,t,n){let r="html"===n.name?"innerHTML":n.name;if(Un||!(t instanceof TypeError)||!Ae(r)||!("trustedTypes"in globalThis))return;Un=!0;let i="function"==typeof Ee()?.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 Fn=new WeakMap;function qn(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=Fn.get(e);void 0===s&&Fn.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 Bn=[["$streams","$stream"],["$updatedCallback","$renderedCallback"]],Gn={$trackDependency:"$dependOn",$untrackDependency:"$untracked"},Kn={name:"diagnostics",install(){c.Bo=Tn,c.Do=Cn,c.So=Wn,c.detail=qn,c.qe=h(c.qe,Dn);let e=c.de;c.de=(t,n)=>{(function(e){void 0!==e.$scan&&_(1);for(let[t,n]of Bn)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=jn(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(`^(?:${zn(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(`^${zn(r)}(?:${zn(l)})*${zn(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){On.delete(e),Pn.has(e)&&Hn(e)}(t)},c.rt=d(p,c.rt,(e,t)=>Object.hasOwn(Gn,t)?_(1701,[t,Gn[t]]):void 0)}},Vn={},Jn=/\.\d/,Qn=new Set(Object.getOwnPropertyNames(Object.prototype)),Xn=0,Yn=!1,Zn=null,er=()=>{Yn=!1,Xn++};function tr(){if(null===Zn)if("function"==typeof MessageChannel){let e=new MessageChannel;e.port1.onmessage=er,e.port1.unref?.(),Zn=()=>e.port2.postMessage(0)}else Zn=()=>setTimeout(er,0);return Yn||(Yn=!0,Zn()),Xn}function nr(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.J){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 rr=class{constructor(e,t){this.active=!1,this.Ce=new Map,this.early=[],this.n=0,this.Ao=-1,this.Dn=new Set,this.Ve=null,this.engine=e,this.Qe=t}ur(){let e=this.engine;this.Ce.clear();let t=this.early;this.early=[];for(let t of this.Qe)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(Vn,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;for(let[n,r,i,s]of t)(null===r||r.y)&&Object.is(e.v(n.p,r),s)&&this.Ft(n,r,i,!0);this.Ce.size>0&&e.we()}prime(e,t){try{t()}catch(t){console.error(`[@wcstack/state] $watch initial evaluation of "${e.t}" threw.`,t),c.at?.(this.engine,{type:"state:watch-error",phase:"prime",path:e.t,error:t})}}Fo(){this.active=!1,this.Ce.clear(),this.early=[]}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)}Ft(e,t,n,r){let i=this.Ce.get(e);void 0===i&&this.Ce.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)}ve(e,t,n,r,i,s){if(this.active){(this.Ve??=new Set).add(e);for(let s of this.Qe){let o=s.p;o.n!==e.n||!o.ee(e)||this.Ft(s,t,s.getter?s.s.get(t??Vn):o===e&&i&&this.engine._t&&(null===r||"object"!=typeof r&&"function"!=typeof r)?n:void 0,!0)}}else if(s)for(let i of this.Qe)i.p===e&&this.early.push([i,t,n,r])}ke(e,t){if(this.active)for(let n of this.Qe)(n.getter||=null!==n.p.getter||n.p.se)&&n.p.n===e.n&&n.p.ee(e)&&this.Ft(n,t,n.s.get(t??Vn),!1)}Jt(e,t){if(!this.active)return;let n=null;for(let r of this.Qe){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.Ft(r,t,void 0,!0):this.Mn(i,e.n+1,t,e=>this.Ft(r,e,void 0,!0)))}}}Fe(){let e=this.Ve;if(this.Ve=null,!this.active||0===this.Ce.size)return;let t=this.Ce;this.Ce=new Map;let n=this.engine,r=[];for(let i of this.Qe){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)=>sr(e[0],t[0]));for(let[t,[s,a,u]]of l){let l,h="evaluate",d=n.u;this.n=a+1,n.Te++;try{if(l=n.v(i.p,t),i.getter&&(i.s.set(t??Vn,l),Object.is(l,s)&&(Jn.test(i.t)||null!==t&&!u&&!(o??=null!==e&&nr(ir(i.p),e)))))continue;if(a>32){r.includes(i.t)||r.push(i.t);continue}n.u=t,c.at?.(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.at?.(n,{type:"state:watch-error",phase:h,path:i.t,error:e})}finally{n.u=d,this.n=0,n.Te--}}}r.length>0&&this.Oo(r)}Oo(e){let t=tr();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.at?.(this.engine,{type:"state:watch-chain-limit",maxDepth:32,paths:n})}}};function ir(e){for(;null===e.getter&&null!==e.d;)e=e.d;return e}function sr(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 or="$streamStatus",lr="$streamError",ar=new Set(Object.getOwnPropertyNames(Object.prototype)),ur=!1;function cr(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 hr=class{constructor(e,t,n){this.engine=e,this.entries=t,this.M=n}set(e,t,n){ur=!0;try{this.engine.T(this.engine.o(`${e}.${t}`),null,n)}finally{ur=!1}}dr(){for(let e of this.entries)this.start(e,!0)}fr(){for(let e of this.entries)e.ut=!1,e.Q?.abort(),e.Q=null}pr(){for(let e of this.entries)e.ut=!1,null!==e.Q&&(e.Q.abort(),e.Q=null),this.set(or,e.name,"idle")}ke(e){let t=this.M.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.M,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.Te++;try{this.start(i,!1)}finally{e.Te--,t.n=0}}}n.length>0&&t.Oo(n)}start(e,t){let n,i=this.engine;if(null!==e.Q&&e.Q.abort(),e.Q=null,null!==e.g){let s=e.g;s.getter=e.args;let o=s.J.slice();dr(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.J)n.n>0&&v(`$stream "${e}": args must not read a wildcard path ("${n.t}").`),(n.t===e||n.t===`${or}.${e}`||n.t===`${lr}.${e}`)&&v(`$stream "${e}": args must not read the stream itself ("${n.t}").`)}(e.name,s,n)}catch(n){dr(s);for(let e of o)e._n(s);if(s.z=r,t)throw n;return this.set(lr,e.name,n),void this.set(or,e.name,"error")}}let s=new AbortController;e.Q=s,i.T(i.o(e.name),null,e.q),this.set(lr,e.name,null),this.set(or,e.name,"active"),this.mr(e,s,n)}async mr(e,t,n){let r=this.engine,i=t.signal,s=()=>!i.aborted&&e.Q===t,o=r.o(e.name),l=this.M.n,a=tr(),u=e=>{tr()===a&&(this.M.n=l);try{e()}finally{this.M.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.Q=null,u(()=>this.set(or,e.name,"done"))}catch(n){if(!s())return;e.Q=null,t.abort(),u(()=>{this.set(lr,e.name,n),this.set(or,e.name,"error")})}}};function dr(e){for(let t of e.J){let n=t.W.indexOf(e);n>=0&&t.W.splice(n,1),t.pt.delete(e)}e.J.length=0,e.z=t}var fr=new WeakMap;function pr(e){let t=fr.get(e);return t?.target===e.target?t:void 0}function mr(e,t){let n=new rr(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("@")||Qn.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 hr(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)||ar.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.`),cr(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,Q: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[or]=i,t[lr]=s,r}(e,t),n),i=fr.get(e);void 0!==i&&(i.M.Fo(),i.Ot.fr()),fr.set(e,{M:n,Ot:r,Ge:i?.Ge??!1,target:t})}function gr(e,t){let n=fr.get(e);if(void 0!==n&&"mounting"!==t&&!document.documentElement?.hasAttribute("data-wcs-server")&&("reset"!==t&&(n.Ge="connected"===t),n.target===e.target)){if("disconnected"===t)return n.M.Fo(),void n.Ot.pr();n.Ge&&(n.M.ur(),n.Ot.dr())}}var yr=["$streamStatus","$streamError"],br={name:"temporal",install(){c.de=h(c.de,mr),c.element=h(c.element,gr),c.ve=h(c.ve,(e,t,n,r,i,s,o)=>pr(e)?.M.ve(t,n,r,i,s,o)),c.ke=h(c.ke,(e,t,n)=>{let r=pr(e);void 0!==r&&(r.M.ke(t,n),r.Ot.ke(t))}),c.Jt=h(c.Jt,(e,t,n)=>pr(e)?.M.Jt(t,n)),c.Fe=h(c.Fe,e=>{let t=pr(e);void 0!==t&&(t.M.Fe(),t.Ot.Fe())}),c.rt=d(p,c.rt,(e,t)=>{let n=t.split(".",1)[0];if(yr.includes(n))return n===t?e.target[t]:e.read(e.o(t),null)}),c.Ae=d(f,c.Ae,(e,t)=>(!ur&&36===t.t.charCodeAt(0)&&yr.includes(t.t.split(".",1)[0])&&v(`"${t.t}" is read-only (the stream runtime owns it).`),!1))}},vr=new WeakMap,wr=!1,_r=/^(?!prototype$)[^\d.*$][^.*]*$/;function $r(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.`)}}vr.set(t,r)}function kr(e){if(null===e||"object"!=typeof e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function Sr(e,t,n){let r=new Map;for(let i of t){kr(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 Nr(e,t,n,r){if(wr||!Array.isArray(r))return!1;let i=vr.get(e.target)?.get(t);if(void 0===i)return!1;let s=e.it(t,n);if(!Array.isArray(s)||s===r)return!1;let o=Sr(t.t,s,i);Sr(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){wr=!0;try{e.T(t,n,l)}finally{wr=!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=_r.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 Cr={name:"list-keys",install(){c.de=h(c.de,$r),c.Ae=d(f,c.Ae,Nr)}},Er=new WeakMap,Ar=new WeakMap,xr="will not graft: the root state failed to initialize.",Tr=new WeakSet,Pr=new WeakMap,Or=["$stream","$streams","$scan","$recursion","$watch","$listKeys","$renderedCallback","$updatedCallback","$behavior","$features"],Mr=["$commandTokens","$eventTokens","$on","$errorCallback"],Lr=e=>`[@wcstack/state] <${ne.tagNames.state} mount="${e}">`,Ir=new Set(["$getAll","$setAll","$resolve","$postUpdate","$dependOn","$eq","$eqIndex"]),jr=e=>e?.element?.isConnected?e:void 0;function Rr(e){let t=Ar.get(e);return void 0!==t&&!Array.isArray(t)&&t.isConnected}function Hr(e,t){let n=Ar.get(t);if(Ar.delete(t),Array.isArray(n))for(let t of n)Dr(t,e)}function Wr(e){let t=Er.get(e.root);t?.get(e.t)===e&&t.delete(e.t)}function zr(e,t){console.error(`${Lr(e.t)} ${t}`),Wr(e),e.Je?.(),e.Je=null}function Ur(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 Dr(e,t){if(Tr.has(t))return zr(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 zr(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)):Ir.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.it(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.Ve(t.o(e),null);e.engine=t;let c=Pr.get(t);void 0===c&&Pr.set(t,c=[]),c.push(e),e.el.isConnected&&Ur(e,"$connectedCallback"),e.Je?.(),e.Je=null}function Fr(e,t){let n=Ar.get(e);if(Array.isArray(n))for(let e of n)zr(e,xr);Ar.set(e,t)}var qr=new WeakMap;function Br(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(ne.bindAttributeName))i='injections (data-wcs="state.<key>: …") are not supported — read the root path in a root getter.';else{let e=Er.get(t);void 0===e&&Er.set(t,e=new Map);let s=e.get(n);if(void 0!==s&&s!==r&&(null===s.engine?s.el.isConnected:jr(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 zr(r,i);if(Er.get(t).get(n)===r){for(let t of Or)if(void 0!==e[t])return zr(r,`${t} is not run in a volume — declare it on the root state.`);for(let t of Mr)void 0!==e[t]&&console.warn(`${Lr(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=jr(Lt.get(t)),i=Ar.get(t);void 0!==n?Dr(r,n):Rr(t)?zr(r,xr):Ar.set(t,[...Array.isArray(i)?i:[],r])})}},Ge(){null!==r.engine&&Ur(r,"$connectedCallback")},Bn(){null!==r.engine&&Ur(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 Gr=new WeakMap,Kr=new WeakMap;function Vr(e,t){let n=e[t];if(void 0===n)return[];Array.isArray(n)||v(`${t} must be an array of state member names.`);let r=new Set;for(let e of n)("string"!=typeof e||""===e)&&v(`${t} entries must be non-empty strings.`),"$"===e[0]&&v(`${t} entry "${e}": internal ($) members are never exposed.`),r.has(e)&&v(`${t} entry "${e}" is duplicated.`),r.add(e);return n}function Jr(e,t){let n=t.host;if(void 0===n||!n.hasAttribute("data-wc-definition"))return null;let r=document.createDocumentFragment();for(let e of[...t.childNodes])r.appendChild(e.cloneNode(!0));let i=t.mode;return{start(t){e.hasAttribute("bind-component")&&v("DCC: a <wcs-state bind-component> cannot define a component (use one mechanism)."),function(e,t,n,r){e.includes("-")||v(`DCC: <${e} data-wc-definition> is not a valid custom element name.`),void 0!==customElements.get(e)&&v(`DCC: <${e}> is already defined.`);let i=function(e){let t=new Map;for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n))for(let e of Object.getOwnPropertyNames(n))"constructor"===e||"$"===e[0]||t.has(e)||t.set(e,Object.getOwnPropertyDescriptor(n,e));let n=e.$stream;if(null!==n&&"object"==typeof n)for(let e of Object.keys(n))t.has(e)||t.set(e,{value:void 0});return t}(r),s=Vr(r,"$bindables"),o=Vr(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(ne.tagNames.state);return a.set(r,o),Gr.set(r,l),null===o&&s.length>0&&console.warn(`[@wcstack/state] DCC: <${e}> declares $bindables but its content has no <${ne.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)},Ge(){},Bn(){},reset(){v("re-setting a DCC definition is not supported: each instance loads its own state.")}}}var Qr=new WeakMap,Xr=new WeakSet,Yr=new WeakMap,Zr=new WeakMap,ei="data-wcs-wired",ti=new WeakMap,ni=new WeakMap,ri=new WeakMap,ii=0,si=new Set,oi={},li=["$watch","$stream","$renderedCallback"],ai=e=>e.split(".",1)[0];function ui(e,t){let n=0;return e.split(".").map(e=>"*"===e?String(t[n++]):e).join(".")}function ci(e,t){let n=e.a,r=ai(e.name);if(!0!==document.documentElement?.hasAttribute("data-wcs-server"))n.removeAttribute(ei);else if(!di(n,r)){let e=n.getAttribute(ei)?.split(" ")??[];e.includes(r)||n.setAttribute(ei,[...e,r].join(" "))}ti.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=Qr.get(n);void 0===i&&Qr.set(n,i=[]),i.push(e),t&&Xr.add(e);let s=Yr.get(n);return void 0===s&&Yr.set(n,s=new Map),s.has(r)||s.set(r,n[r]),Zr.get(n)?.(),!1}function hi(e){return e.localName.includes("-")&&null!==e.querySelector(`:scope > ${ne.tagNames.state}[bind-component]`)}function di(e,t){let n=e.getAttribute(ne.bindAttributeName);return null!==n&&new RegExp(`(^|;)\\s*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[.#:]`).test(n)}function fi(e){let t=e.parentElement;for(;null!==t&&!hi(t);)t=t.parentElement;let n=Lt.get(t??e.getRootNode()),r=n?.element;(r?.isConnected?r.V:null===t)&&(null===t?Dt(e):jt(n,e))}var pi=new Set;function mi(e,t){pi.has(e)||(pi.add(e),console.warn(`[@wcstack/state] ${t}`))}var gi=(e,t)=>t in e.state;function yi(e,t){let n=bi(e.state,t);return void 0!==n&&(void 0!==n.get||void 0!==n.set||"function"==typeof n.value)}function bi(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 vi(e,t,n){if(null!==n.getter)return;let r,i=e.host,s=i.engine,o=ai(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=wi(e,l.r);return 0===t.n?n:(s.resolve(ui(o.t,[...s.H(n),...i.H(Z(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();_i(e,l.e,()=>s.T(o,r,n)),e.dn=t}),t.n>0&&(t.A=i.je++),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?gi(i,o):yi(i,o))return;r=l.me}else{if(null===t||null!==n.d||"$"===o[0]||gi(i,o))return;l=t,r=s.o(`${t.me.t}.${o}`)}let a=l.r,u=l;n.getter=()=>s.v(r,wi(e,a)),n.ie=t=>{_i(e,u,()=>s.T(r,a,t)),e.dn=n},e.dt.set(n,{e:l,p:r,r:a})}function wi(e,t){return null!==t&&!t.y&&v(`The host row of <${e.host.el.localName}> was removed.`),t}function _i(e,t,n){let r=si.has(e.x);si.add(e.x),e.from=t;try{n()}finally{r||si.delete(e.x),e.from=null}}var $i=(e,t)=>t||!si.has(e.m.x)||null!==e.m.from&&e.m.from!==e.e;function ki(e,t){if(e.fn===t||null===e.host.engine)return;e.fn=t,ii+=t?1:-1;let n=e.host.engine,r=ri.get(n);void 0===r&&ri.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=ai(o);if(o!==a&&!gi(n,a))continue;let u=r.o(`${t.me.t}.${o}`);if(null===u.getter)Ci(r,u,t.me);else if(!Si.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&&Ci(n,r,i.me),n.P.be(n,r,i.r);e.re.size>0&&n.we(),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;mi(`${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 Si=new WeakSet;function Ni(e,t,n,r){let i=ri.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 Ci(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=Ni(e,n,e.u,t);return null===o?void 0:o.x.read(o.re.get(t),null)},Si.add(t.getter),t.ie=o=>{let l=null===s()?Ni(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===bi(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.je++)}function Ei(e,t,n,r,i,s){if(null!==t.getter)return e.P.be(e,t,n),void e.we();if("*"===t.s){if(null===n)return;if(n.R=n.l.C[n.b],e.P.Yt(n),null!==n.c)for(let t of n.c.values())e.Y(t)}else e.En(t,n);c.ve?.(e,t,n,r,i,s),e.Ve(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.be(t,n,null):t.nn(n.h[n.n],e=>t.P.be(t,n,e)));t.we()}function xi(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=ai(a);if("$"===e[0]||gi(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(Z(r,e).b);c.resolve(ui(a,h),null);let d=c.rp,f=c.rr;d.n>0&&null===f||Ei(c,d,f,i,s,o)}function Ti(e,t,n,r,i,s,o){if(0===ii)return;let l=si.has(e);si.add(e);try{let l=ni.get(e);!o&&void 0!==l&&l.fn&&!si.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(ui(o.p.t+t.t.slice(l.t.length),u),null);let c=a.rp,h=a.rr;c.n>0&&null===h||_i(e,o.e,()=>Ei(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.be(r,i,n.r),r.we())}(l,t);let a=ri.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:Z(n,e.n));if(void 0!==a)for(let l of[...a])$i(l,o)&&xi(l,e,t,n,r,i,s)}else if(e.ee(t))for(let[e,r]of[...l])if(0===t.n||Z(e,t.n)===n)for(let e of[...r])$i(e,o)&&Ai(e)}finally{l||si.delete(e)}}async function Pi(e,t,n,r,i){if(r===oi)return;let s=y(r);s&&await s;let o=ti.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 <${ne.tagNames.state} bind-component="${o.pe}">.`),null!==l&&ki(l,!1),null!==l&&function(e,t,n){let r=e.x,i=`[${ne.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.j)l(t.a);else for(let e of t.j.G)a(t.j,e.S);for(let e of r.oe.values())for(let t of[e.$,...e.D??[]])null!==t&&a(t,t.S);for(let t of e.B)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.B.includes(n)&&(s(n)||r.Wt&&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.B=e.B.filter(e=>e.parentNode===n),t.isConnected?await Oi(e,r):r()}(l,e,n,i);let a=new te(r,new qt);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,B:[],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,ni.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=ai(e.E);gi(n,t)&&(e.E!==t||yi(n,t))&&mi(`${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)&&mi(`${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=li.filter(e=>void 0!==n.state[e]);o.length>0&&mi(`${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.ot;t.ot=n=>{vi(e,s,n),l.call(t,n)};let a=[...t.I.all()];for(let t of a)vi(e,s,t);for(let e of a)l.call(t,e);let u=t.Xt;t.Xt=()=>{(function(e){for(;void 0!==e;e=ni.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),ki(u,!0),Tr.add(a),Hr(a,n));let d=c.hr?.(n);It(a,n),d?.(),u.B=[...n.childNodes],Ft(),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.Se("$connectedCallback"),h&&e.isConnected&&c.element?.(a,"connected")):ki(u,!1)}async function Oi(e,t){ki(e,!0);for(let t of e.fe)Ai(t);t?.(),!e.broken&&(await e.x.Se("$connectedCallback"),null===e.host.engine&&e.el.isConnected&&c.element?.(e.x,"connected"))}function Mi(e,t){let n=e.getAttribute("bind-component");if(null===n)return function(e,t){return e.connectedCallbackPromise.catch(()=>{let n=Lt.get(t)?.element;if(!(e.V||void 0!==n&&n!==e&&n.isConnected)){Fr(t,e);for(let e of qr.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:ti.get(s)?.O;return t?.el===e?t:null},l=t=>{throw i&&Fr(r,e),t},a=!1;return{Mt:()=>(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(`<${ne.tagNames.state} bind-component> takes its state from <${i}>.${t}: it cannot also load one (state / src / json / an inline script).`),await Le(n).whenDefined(i);let s=ti.get(n);if(void 0!==s)return s.pe!==t&&v(`<${i}> already has a <${ne.tagNames.state} bind-component="${s.pe}">.`),s.state;let o=()=>(Qr.get(n)??[]).filter(e=>ai(e.name)===t),l=di(n,t);if(l&&0===o().length&&fi(n),0===o().length&&(l||((e,t)=>!0===e.getAttribute(ei)?.split(" ").includes(t))(n,t))){let e;await new Promise((r,s)=>{Zr.set(n,r),e=function(e,t){Rr(e)&&t();let n=qr.get(e)??new Set;return qr.set(e,n.add(t)),()=>n.delete(t)}(n.getRootNode(),()=>s(new Error(`[@wcstack/state] <${i}>.${t} will not mount: the root state failed to initialize.`)))}).finally(()=>e())}Zr.delete(n);let a=o(),u=Yr.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 (${ne.bindAttributeName}="${t}: path").`);return queueMicrotask(()=>{throw e}),oi}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:Xr.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 ti.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 <${ne.tagNames.state}> to be a direct child of a custom element.`))).catch(l),async start(t,n){await Pi(e,s,i?r:s,t,()=>{a=!0,n()}).catch(e=>{let t=o();return!a&&null!==t&&(t.broken=!0),l(e)})},Ge(){let t=o();null!==t?Oi(t).catch(e=>console.error(e)):a?Promise.resolve().then(()=>{if(e.parentNode===r)return Pi(e,s,i?r:s,ti.get(s).state,()=>{})}).catch(e=>console.error(e)):Zr.has(s)&&fi(s)},Bn(){let e=o();null!==e&&(ki(e,!1),!e.broken&&(e.x.Se("$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 Li={name:"scopes",install(){c.ct=d(m,c.ct,Br),c.ct=d(m,c.ct,Jr),c.ct=d(m,c.ct,Mi),c.ar=ci,c.Eo=hi,c.element=h(c.element,(e,t)=>{if("mounting"!==t)return function(e,t){let n=Pr.get(e)??[];if("disconnected"===t)for(let e of n)Wr(e);else if("reset"!==t&&jr(Lt.get(e.root))===e){Hr(e,e.root);for(let e of n)Er.get(e.root).has(e.t)||Er.get(e.root).set(e.t,e)}}(e,t);let n=e.element.getRootNode();Hr(e,n),function(e,t){let n=t.host,r=void 0===n?void 0:Gr.get(n);void 0!==r&&Kr.set(e,{host:n,def:r})}(e,n)}),c.ve=h(c.ve,(e,t,n,r,i,s)=>{(function(e,t,n,r){let i=Kr.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),Ti(e,t,n,r,i,s,!1)}),c.ke=h(c.ke,(e,t,n)=>Ti(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=Pr.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=ni.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||(wi(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=Pr.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=ri.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)}}},Ii="$recursion",ji=new WeakMap,Ri=new WeakSet,Hi=new WeakSet,Wi=0,zi=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ui=e=>`[wcs/recursion-${e}]`;function Di(e,t){let n=n=>v(`${Ui("declaration-invalid")} ${Ii} ${e} "${String(t)}" ${n}`);("string"!=typeof t||""===t)&&v(`${Ui("declaration-invalid")} ${Ii} ${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 Fi=(e,t)=>`${e.l}.*${e.step.repeat(t)}`;function qi(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 Bi(e,t,n){let r=qi(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.`),Fi(e,i.k)+r}function Gi(e,t,n){let r=new Set,i=new Set,s=(e,n,s)=>!(!Array.isArray(e)||0===e.length||(r.has(e)&&v(`${Ui("cycle")} "${n}" is reachable from itself: the data under "${t.l}" must be a tree.`),i.has(e)&&v(`${Ui("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(`${Ui("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(`${Fi(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 Ki(e,t){let n=function(e){let t=e[Ii],n=[],r=new Set;for(let t=e;null!==t&&t!==Object.prototype;t=Object.getPrototypeOf(t))for(let e of Object.getOwnPropertyNames(t))!r.has(e)&&e.includes("**")&&n.push([e,Object.getOwnPropertyDescriptor(t,e)]),r.add(e);if(void 0===t)return n.length>0&&z(n[0][0]),null;(null===t||"object"!=typeof t||Array.isArray(t))&&v(`${Ui("declaration-invalid")} ${Ii} must be an object mapping one anchor path to its repeating sub-path.`);let i=Object.entries(t);1!==i.length&&v(`${Ui("declaration-invalid")} ${Ii} must declare exactly one anchor (it declares ${i.length}).`);let s=Di("anchor",i[0][0]),o=Di("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(`${Ui("declaration-invalid")} "${e}": a recursive key is a getter without a setter.`),c.set(n,t.get),h.push([new RegExp(`^${zi(s)}((?:${zi(u)})*)${zi(n)}$`),n])}return{l:l,step:u,key:a,families:c,matchers:h,owners:new Map,nodeList:new RegExp(`^${zi(l)}((?:${zi(`.*.${a}`)})*)$`)}}(t),r=ji.has(e);null!==n?(r||Wi++,ji.set(e,n),Hi.add(e),Ri.has(e)||function(e){Ri.add(e);let t=e,n=t.ot;t.ot=r=>{let i=ji.get(e);if(r.t.includes("**")){let t=e.I.jt(r.t)===r;return void(Hi.has(e)||void 0===i&&t?r.getter=()=>z(r.t):t||n.call(e,r))}if(void 0!==i&&null===r.getter)for(let[e,n]of i.matchers)if(e.test(r.t)){r.getter=i.families.get(n),r.n>0&&(r.A=t.je++),i.owners.set(r,i.l+".**"+n);break}n.call(e,r)};let r=t.resolve;t.resolve=(t,n)=>{let i=ji.get(e);return r.call(e,void 0!==i&&t.includes("**")?Bi(i,t,n):t,n)};let i=t.getAll;t.getAll=(n,r)=>{let s=ji.get(e);if(void 0===s||!n.includes("**"))return i.call(e,n,r);if(void 0===r)return i.call(e,Bi(s,n,t.u));(!Array.isArray(r)||r.length>0)&&v(`${Ui("getall-form")} $getAll("${n}", indexes) with "**" takes either no indexes (this depth) or [] (every depth).`);let o=qi(s,n),l=[];return Gi(e,s,(t,n)=>{for(let r of i.call(e,Fi(s,t)+o,e.H(n)))l.push(r)}),l};let s=t.yn;t.yn=(n,r,i,o)=>{let l=ji.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(`${Ui("setall-form")} $setAll("${n}", indexes, …) with "**" takes no partial prefix: pass [] to write every node.`),("function"==typeof i||!0===o?.spread)&&v(`${Ui("setall-form")} $setAll("${n}", [], value) with "**" takes a plain value (no mapper, no spread).`),t.Le>0&&_(8);let a=qi(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(`${Ui("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(`${Ui("readonly")} "${n}" writes into the recursive getter "${l.l}.**${e}".`)}let h=[];Gi(e,l,(e,t)=>h.push([e,t]));let d=0;for(let[t,n]of h)d+=s.call(e,Fi(l,t)+a,e.H(n),i);return d}}(e)):r&&(ji.delete(e),Wi--)}function Vi(e,t){if(0===Wi)return!1;let n=ji.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(`${Ui("readonly")} "${t.t}" writes into the recursive getter "${r}".`)}return!1}var Ji={name:"recursion",install(){c.de=h(c.de,Ki),c.element=h(c.element,(e,t)=>{("mounting"===t||"reset"===t)&&function(e){Hi.delete(e)}(e)}),c.Ae=d(f,c.Ae,Vi)}},Qi="4.1.1",Xi=e=>e.split(".").slice(0,2).join("."),Yi=class extends Jt{static find(e){return e.querySelector?.(ne.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 Xi(this.version)===Xi(Qi)}};function Zi(e){let t=ne.tagNames.ssr;void 0===e.get(t)&&e.define(t,class extends Yi{})}var es=()=>ne.tagNames.ssr,ts=Symbol.for("wcstack.ssr.snapshotBuilder"),ns=()=>!0===document.documentElement?.hasAttribute("data-wcs-server"),rs=e=>document.createComment(e),is=(e,t)=>null!==e&&8===e.nodeType&&e.data===t,ss=(e,t)=>null!==e&&8===e.nodeType&&e.data.startsWith(t),os=new WeakMap,ls=new WeakMap,as=new WeakMap,us=new WeakSet,cs=new WeakMap;function hs(e,t){let n=[];for(let r=e;null!==r&&(n.push(r),r!==t);r=r.nextSibling);return n}function ds(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 fs=e=>null===e.B?e.Ke:e.B[e.B.length-1];function ps(e,t,n){let r=[rs(null===n?"wcs-[":`wcs-[:${n}`)];for(let e of t)null===n&&r.push(rs("wcs-|")),r.push(...hs(e.Ke,fs(e)));r.push(rs("wcs-]")),e.after(...r);for(let e of r)us.add(e)}function ms(e){if(e instanceof ot){ps(e.S,e.Re,null);for(let t of e.Re)gs(t);return}let t=e.O;null!==t&&(ps(e.G[e.G.length-1].S,[t],e.b),gs(t))}function gs(e){if(null!==e.c)for(let t of e.c)ms(t)}var ys=new Set(["script","style","template","textarea","title"]),bs="data-wcs-raw",vs=e=>ys.has(e.localName)||e.localName===es();function ws(e){for(let t of Array.from(e.childNodes))3===t.nodeType?""===t.data?t.replaceWith(rs("wcs-e")):null!==t.nextSibling&&3===t.nextSibling.nodeType&&t.after(rs("wcs-s")):1===t.nodeType&&!vs(t)&&ws(t)}var _s=0;function $s(e,t){let n=e.getRootNode(),r=[t];for(let e of ls.get(n)??[])e!==t&&!0===e.element?.hasAttribute("bind-component")&&r.push(e);let i=new Map;for(let e of r){let t=os.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.D)for(let e of t.D)n.set(e.S,e);for(let t of e.ce.values())for(let e of t)if(null!==e.j)for(let t of e.j.G)n.set(t.S,e.j);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),ms(t))}}for(let e of Array.from(n.querySelectorAll("*"))){let t=as.get(e);if(void 0!==t){let n=document.createTreeWalker(e,133,{acceptNode:e=>us.has(e)||1===e.nodeType&&t.has(e)&&Es(e)?2:1}),r=[];for(let e=n.nextNode();null!==e;e=n.nextNode()){let n=e.previousSibling;(3===e.nodeType?e.data.includes("{{")&&!(vs(e.parentNode)?cs.has(e):t.has(n)&&ss(n,"wcs-t:"))&&(cs.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);vs(e)&&n.some(e=>cs.has(e))&&e.setAttribute(bs,n.map(e=>cs.has(e)?`{{ ${cs.get(e)} }}`:8===e.nodeType?`\x3c!--${e.data}--\x3e`:e.textContent).join(""))}ws(9===n.nodeType?n.body:n);let s=document.createElement(es());s.setAttribute("version",Qi);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"}${_s++}`;e.replaceWith(rs(`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(ds(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(ds(t,l,o))}e.before(s)}function ks(e){!function(e){if(null!==e.querySelector(ne.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=>cs.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(`${ne.tagNames.state}[enable-ssr]`))){if(t.hasAttribute("mount")||t.hasAttribute("bind-component")||t.previousElementSibling?.localName===es())continue;let e=t.engine;null!=e&&$s(t,e)}}var Ss=Symbol.for("wcstack.state.ssr.impl"),Ns=new Map,Cs=new WeakMap,Es=e=>!0===c.Eo?.(e),As=e=>1===e.nodeType&&!vs(e)&&!Es(e),xs=e=>e.f.flat().concat(e.K??[]),Ts=e=>{for(let t of xs(e))t.remove()};function Ps(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&&!is(l,"wcs-]");){let e=l.nextSibling;if(is(l,"wcs-|"))o.push([]),l.remove();else{0===o.length&&o.push([]);let n=o[o.length-1];ss(l,"wcs-[")?e=Ps(l,t,n):(n.push(l),As(l)&&Os(l,t))}l=e}let a={branch:void 0===r[1]?null:Number(r[1]),f:o,K:l??s.appendChild(rs("wcs-]"))},u=xs(a);l=a.K.nextSibling;for(let e of u)n?.push(e),t&&Nt.add(e);return t&&null!==i?Ns.set(i,a):Ts(a),l}function Os(e,t){for(let n=e.firstChild;null!==n;)ss(n,"wcs-[")?n=Ps(n,t):(As(n)&&Os(n,t),n=n.nextSibling)}function Ms(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=rs(`@@:${decodeURIComponent(e.slice(6))}`),n=i.nextSibling;for(;null!==n&&!is(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]?ds(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&&!vs(i)&&(Es(i)?Cs.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||zs(n)||"template"===n.localName);n=n.previousSibling)e.unshift(n);let n=0,r=0;if(e.forEach((e,t)=>{ss(e,"wcs-[")?r++:is(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(ss(r,"wcs-["))i++;else if(is(r,"wcs-]")&&0===i--){t.prepend(...e.slice(n));break}}}(e),Os(e,n)}function Ls(e){let t=Cs.get(e);if(void 0===t||(Cs.delete(e),Ms(e,t.ssr,t.Oe),!t.Oe))return null;let n=c.Oe;return c.Oe=Fs,()=>{c.Oe=n,Is()}}function Is(){for(let e of Ns.values())Ts(e);Ns.clear()}function js(e){let t=[];for(let n=document.createTreeWalker(e,128);n.nextNode();)t.push(n.currentNode);return t}function Rs(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 Hs(e,t,n){if(ns()){if(n instanceof Array){for(let e=n.length;e-- >0;)mt(n[e])&&n.splice(e,1);let e=t;if(n.some(gt))us.add(e);else if(e.localName.includes("-")&&!Es(e)){let t=new Map;for(let n=document.createTreeWalker(e,133);n.nextNode();)t.set(n.currentNode,n.currentNode.data);as.set(e,t)}return}if("string"==typeof n){if(cs.set(t,n),vs(t.parentNode))return;let e=rs(`wcs-t:${encodeURIComponent(n)}`),r=rs("wcs-/t");return t.before(e),void t.after(r)}let r=os.get(e);void 0===r&&os.set(e,r=new Map),r.set(t,n);let i=t.getRootNode(),s=ls.get(i);return void 0===s&&ls.set(i,s=new Set),void s.add(e)}if("string"!=typeof n&&Ns.size>0){let e=Ns.get(n);void 0!==e&&(Ns.delete(n),Ns.set(t,e))}}var Ws=e=>null!==e&&8===e.nodeType&&[ne.commentIfPrefix,ne.commentElseIfPrefix,ne.commentElsePrefix].includes(e.data),zs=e=>3===e.nodeType&&""===e.data.trim(),Us=e=>(Ns.get(e)?.K??e).nextSibling;function Ds(e,t){if(t.length!==e.ln.childNodes.length)return!1;let n=e.On;for(let r=0;r<n.length;r++){let i=n[r],s=e.ln,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=Us(o)}e.ko[r]=o}return!0}function Fs(e,t,n){if(0===Ns.size)return null;let r=t,i=0;if(!n){let e=ne.commentIfPrefix;if(!is(t,e))for(let n=t.previousSibling;null!==n&&1!==n.nodeType&&(Ws(n)&&i++,!is(n,e));n=n.previousSibling);for(let n=t.nextSibling;!Ns.has(r)&&null!==n&&!is(n,e)&&1!==n.nodeType;n=n.nextSibling)Ws(n)&&(r=n)}let s=Ns.get(r);if(void 0===s)return null;if(!n&&s.branch!==i)return Ns.delete(r),Ts(s),null;let o=s.f.shift();if(0===s.f.length&&Ns.delete(r),s.K?.replaceWith(...hs(t,r)),s.K=null,void 0===o)return null;let l=[];for(let e=0;e<o.length;e++){let t=Ns.get(o[e]);if(l.push(o[e]),void 0!==t)for(;e<o.length&&o[e]!==t.K;)e++}if(!Ds(e,l)){let n=(e.In?e.root:e.ln).cloneNode(!0);l=e.In?[n]:[...n.childNodes],Ds(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 qs={name:"ssr",install(){c.jn=Hs,c.hr=Ls;let e=c.element;c.element=(t,n)=>{"mounting"===n&&function(e){let t=e.element;if(!t.hasAttribute("enable-ssr")||ns())return;let n=t.previousElementSibling,r=n?.localName===es(),i=r?n.getAttribute("version"):null,s=null===i||Xi(i)===Xi(Qi);if(s){let t=e,n=t.Se;t.Se=(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] <${es()} version="${i}"> does not match ${Qi}: 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(`[${bs}]`)))e.textContent=e.getAttribute(bs),e.removeAttribute(bs);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&&!Es(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 > ${ne.tagNames.state}[bind-component]`).getAttribute("bind-component");r.set(t,n=[]);for(let r of le(t.getAttribute(ne.bindAttributeName)??"")){let t=r.Ze;r.$e[0]===s&&n.push([e?Rs(e,t,1,0):t,r.$e.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:Rs(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]:Rs(r,s[2],2,1)??s[2]};for(let t of js(e).reverse()){let e=/^@@wcs-(\w+)-start:([\s\S]*)/.exec(t.data);if(null===e)continue;let r=t.nextSibling;for(;null!==r&&!is(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]?[rs(`@@:${s(t,e[2],n)}`)]:[])}}let o=(e,n)=>{for(let r of js(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=ne.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):Ms(d,n,s),n.remove(),s&&(c.Oe=Fs,queueMicrotask(()=>{Is(),c.Oe=null}))}(t),e?.(t,n)},function(){let e=globalThis;e[Ss]={build:ks,reset(){_s=0}},void 0===e[ts]&&(e[ts]={protocol:"wcs-ssr-snapshot",version:1,build:t=>e[Ss].build(t),reset:()=>e[Ss].reset()})}(),c.To=h(c.To,Zi);for(let e of Yt())Zi(e)}},Bs="__WCSTACK_DEVTOOLS_HOOK__",Gs=null,Ks=new Set,Vs=(e,t,n)=>({absolutePathInfo:{pathInfo:{path:t.t},stateElement:e.element},listIndex:null===n?null:{indexes:e.H(n)}}),Js=new WeakMap,Qs=0,Xs=new WeakMap;function Ys(e){if(null===Gs)return;let t=Xs.get(e),n=Ks.has(e)?function(e,t){let n=new Map,r=new Set,i=(r,i,s,o,l,a)=>{if(5===r)return;let u=function(e,t){return 0===e?"textContent":2===e?`class.${t}`:3===e?`attr.${t}`:4===e?`style.${t}`:t}(r,i),c=0===o.n?null:l,h=`${(e=>{let t=Js.get(e);return void 0===t&&Js.set(e,t=++Qs),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:Vs(e,o,c)})},s=e=>i(e.i,e.name,e.a,e.o,e.r,e.on()),o=e=>{if(!r.has(e)){if(r.add(e),null!==e.he)for(let t of e.he)s(t);if(e instanceof Qe&&null!==e.fe){let t=e.F.Xe;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 ot){i(-1,"for",e.S,e.l.o,e.l.ae,"for");for(let t of e.Re)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.j&&l(e.j);for(let t of e.oe.values())if(null!==t.$&&l(t.$),null!==t.D)for(let e of t.D)l(e);return n}(e,t):new Map;if(void 0!==t)for(let[e,r]of t)n.has(e)||Gs({type:"state:binding-removed",...r});for(let[e,r]of n)(void 0===t||!t.has(e))&&Gs({type:"state:binding-added",...r});Xs.set(e,n)}function Zs(e){let t=Lt.get(e);if(void 0===t)throw new Error("[@wcstack/state] devtools: no state tree on this root");return t}function eo(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.Pe.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 to=new WeakSet,no=new WeakMap;function ro(e,t){if(("mounting"===t||"reset"===t)&&function(e){let t=(t,n)=>{if(to.has(t))return;to.add(t);let r=t.emit;t.emit=(...i)=>(null!==Gs&&Gs({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.Pe.values())t(n,"event")}(e),"connected"===t){if(Ks.has(e))return;Ks.add(e),Gs?.({type:"state:element-registered",rootNode:e.root,element:e.element}),Ys(e)}else"disconnected"===t&&(Ks.delete(e),Ys(e),Gs?.({type:"state:element-unregistered",rootNode:e.root,element:e.element}))}function io(e,t,n,r,i,s){if(null===Gs)return;let o=Vs(e,t,0===t.n?null:n),l=no.get(e);void 0===l&&no.set(e,l=new Set),l.add(o),s&&Gs({type:"state:write",absoluteAddress:o,value:i,oldValue:r,hasOldValue:!0})}function so(e){if(null===Gs)return;let t=no.get(e);no.delete(e),void 0!==t&&Gs({type:"state:update-batch",addresses:t}),Ys(e)}function oo(e,t,n){Gs?.({type:"state:binding-apply-error",path:n.o.t,bindingType:n.on(),error:t})}var lo={"*":["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 ao(e,t){let n=e.localName;if(n.includes("-"))return null;let r=(e=>[...lo["*"],...Object.hasOwn(lo,e)?lo[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())}([gn,Kn,br,Cr,Li,Ji,qs,{name:"devtools",install(){c.element=h(c.element,ro),c.ve=h(c.ve,io),c.Fe=h(c.Fe,so),c.qe=h(c.qe,oo),function(){if(typeof document>"u"||document.documentElement?.hasAttribute("data-wcs-server"))return;let e=globalThis,t=e[Bs]??(e[Bs]=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:Qi,getStateElements:()=>[...Ks].map(eo),overlays:()=>[],keyedSubscriptions:e=>function(e){let t=[];for(let n of e.I.all()){let r=n._,i=n.Ie?.length??0;if((null===r||0===r.size)&&0===i)continue;let s,o=0;if(null!==r)for(let e of r.values())o+=e.size;try{s=0===n.n?e.v(n,null):void 0}catch{s=void 0}t.push({path:n.t,tracked:!1,rows:o,keys:null===r?0:r.size,lists:i,lastValue:s})}return t}(Zs(e)),keys(e){let t=Zs(e).target;return Object.keys(t).filter(e=>{if(e.includes("*")||"$"===e[0])return!1;let n=Object.getOwnPropertyDescriptor(t,e);return void 0!==n.get||"function"!=typeof n.value})},read(e,t,n){let r;return Zs(e).element.createState("readonly",e=>{r=e.$resolve(t,n??[])}),r},write(e,t,n,r){Zs(e).element.createState("writable",e=>{e.$resolve(t,r??[],n)})},_setSink(e){let t=null===Gs&&null!==e;Gs=e,null===e&&(Xs=new WeakMap),c.at=e&&((e,t)=>Gs?.({...t,stateElement:e.element})),t&&queueMicrotask(()=>{for(let e of Ks)Ys(e)})}})}()}},{name:"native-commands",install(){c.or=ao}}]),function(e=customElements){(function(){let e=globalThis;void 0===e[Ht]&&(e[Ht]={protocol:"wcs-binder",version:1,bind:Dt})})(),Yt().includes(e)||Xt.push(new WeakRef(e));let t=ne.tagNames.state;void 0===e.get(t)&&e.define(t,class extends Qt{}),c.To?.(e)}();const uo={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"},co=!1,ho=[".html"];function fo(){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 po(e,t){if(t&&"cause"in t)throw new Error(`[@wcstack/router] ${e}`,{cause:t.cause});throw new Error(`[@wcstack/router] ${e}`)}let mo=class extends Error{fallbackPath;constructor(e,t){super(e),this.fallbackPath=t}};const go={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 yo(e){const t={};for(const[n,r]of new URLSearchParams(e))t[n]=r;return Object.freeze(t)}function bo(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 vo={static:2,param:1,"catch-all":0};let wo=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&&po(`${uo.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&po(`${uo.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+=vo[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(go).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=!1,t.hasGuard&&(this._guardFallbackPath=t.guardFallback||"/",this.enableGuard())}enableGuard(){this._hasGuard||(this._hasGuard=!0,this._guardFallbackPath||="/",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||po(`${uo.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:yo(e.search??""),routeName:e.routes[e.routes.length-1]?.name??""})}(e));if("string"==typeof r&&""!==r)throw new mo("Navigation cancelled by guard.",r);if(!r)throw new mo("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof r?r:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new mo("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}};const _o="data-wcs-ssr",$o="data-wcs-ssr-link",ko="@@wcs-route-ph:",So="@@wcs-route-start:",No="@@wcs-route-end:";let Co=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=fo();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new wo(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||po(`${uo.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(`${No}${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()}enableGuard(){this._core.enableGuard()}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):po(`${uo.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&&po(`${uo.route} with fallback attribute must be a direct child of ${uo.router}.`),e.fallbackRoute&&po(`${uo.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 Eo=Symbol.for("wcstack.trustedTypes.policy"),Ao=Symbol.for("wcstack.trustedTypes.internal"),xo="wcstack";function To(){const e=globalThis[Eo];return null===e||"object"!=typeof e?null:e}let Po=!1;function Oo(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(xo,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){"function"!=typeof To()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${xo}". Allow it in the CSP (\`trusted-types ${xo};\`), 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=To(),i=r?.createHTML;return"function"==typeof i?(Po||(Po=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${xo}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${xo};\` in the CSP to avoid this. See docs/csp.md section 7.`)),i.call(r,e)):e}const Mo=new Map;let Lo=class extends HTMLElement{_uuid=fo();constructor(){super()}async _loadTemplateFromSource(e){try{const t=await fetch(e);t.ok||po(`${uo.layout} failed to fetch layout from source: ${e}, status: ${t.status}`);const n=await t.text();return Mo.set(e,n),n}catch(t){po(`${uo.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(`${uo.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(e)Mo.has(e)?n.innerHTML=Oo(Mo.get(e)||""):n.innerHTML=Oo(await this._loadTemplateFromSource(e)||"");else if(t){const e=this._loadTemplateFromDocument(t);e?n.innerHTML=Oo(e):console.warn(`${uo.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")&&co}get name(){return this.getAttribute("name")||""}},Io=class extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||po(`${uo.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")&&co}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}};const jo=new Set(["props","states","attr",""]);function Ro(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 Ho(e,t){e.hasAttribute("data-bind")||po(`${e.tagName} has no 'data-bind' attribute.`);const n=e.getAttribute("data-bind")||"";jo.has(n)||po(`${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&&Ro(e,t,r)}).catch(()=>{po(`Failed to define custom element: ${i}`)}):Ro(e,t,r)}const Wo=Symbol.for("wcstack.binder");function zo(){const e=globalThis[Wo];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}const Uo=Symbol.for("wcstack.binder.pending"),Do=Symbol.for("wcstack.binder.taken");function Fo(){const e=globalThis;let t=e[Do];return void 0===t&&(t=new WeakSet,e[Do]=t),t}function qo(e,t){const n=zo();return null===n?(function(){const e=globalThis;let t=e[Uo];return void 0===t&&(t=[],e[Uo]=t),t}().push(e),!1):(Fo().add(e),n.bind(e,t),!0)}const Bo={range:!0};function Go(e,t){for(const n of e.routeChildNodes)t.add(n.placeHolder).add(n.endMarker),Go(n,t);return t}function Ko(e){const t=e.placeHolder,n=e.endMarker,r=null!==n.parentNode&&n.parentNode===t.parentNode&&!!(4&t.compareDocumentPosition(n)),i=r?null:Go(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 Vo=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||po(`${uo.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(`${uo.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!==zo())for(const t of e)1===t.nodeType&&qo(t,Bo)}(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=>{Ho(t,e)}),t.hasAttribute("data-bind")&&Ho(t,e))}};function Jo(){return document.createElement(uo.layoutOutlet)}const Qo="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function Xo(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)),po(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 ${Qo}`:`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 ${Qo}`}(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:(console.error(`${uo.guardHandler}: the <script type="module"> has no default-exported function, so the route's guard redirects every navigation.`),t.notifyGuardHandlerLoadFailed())}).catch(e=>{console.error("loadGuardHandler failed:",e),t.notifyGuardHandlerLoadFailed()})}function Yo(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 Zo(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===uo.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),Yo(r,a),n.push(a),o=a.placeHolder,l=a}else{if(a===uo.guardHandler){if(n.length>0){const e=n[n.length-1],t=l.querySelector('script[type="module"]');t&&(e.enableGuard(),Xo(t,e))}continue}if("template"===a){s.appendChild(l);continue}if(a===uo.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=Jo();r.layout=n,o=r,l=t}}const u=await Zo(e,l,n,r);l.replaceChildren(),l.appendChild(u),s.appendChild(o)}else s.appendChild(t);return s}async function el(e){const t=new Map;return await Zo(e,e.template.content,[],t)}const tl=new WeakSet;function nl(e){return!1!==e.checkVisibility?.()}function rl(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=go[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)rl(i,t,n,r)}function il(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)rl(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 sl=null,ol=null;function ll(){const e=ho;return 0===e.length?null:(sl===e&&ol||(sl=e,ol=new RegExp(`\\/[^/]+(?:${e.map(e=>e.replace(/\./g,"\\.")).join("|")})$`,"i")),ol)}function al(e){let t=e||"/";t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/");const n=ll();return n&&(t=t.replace(n,"")),""===t&&(t="/"),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function ul(e,t){let n=e;return""!==t&&(e===t?n="":e.startsWith(t+"/")&&(n=e.slice(t.length))),""===n?"/":n}function cl(e){let t=e||"";if(!t)return"";t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/");const n=ll();return n&&(t=t.replace(n,"")),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),"/"===t?"":t}function hl(e){if(null!==e.held)return;const t=Ko(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 dl(e){e.clearParams(),hl(e)}function fl(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=>{Ho(t,e.typedParams)}),n.hasAttribute("data-bind")&&Ho(n,e.typedParams),n.querySelectorAll(uo.layoutOutlet).forEach(t=>{t.assignParams(e.typedParams)}),n.tagName.toLowerCase()===uo.layoutOutlet&&n.assignParams(e.typedParams)}}const pl=new WeakSet;function ml(e){const t=e.placeHolder;null!==t.parentNode&&(pl.has(e)||null!==e.endMarker.parentNode?(hl(e),t.after(e.held),e.held=null):t.after(...e.childNodeArray,e.endMarker),pl.add(e))}const gl=Symbol.for("wcstack.transition-runner");const yl=new WeakSet,bl="data-wcs";function vl(e,t,n){!yl.has(e)&&function(e){return e.hasAttribute(bl)||null!==e.querySelector(`[${bl}]`)}(e)&&(yl.add(e),function(e){"complete"===document.readyState?e():window.addEventListener("load",e,{once:!0})}(()=>{var r;null!==zo()||(r=e,Fo().has(r))||console.warn(`[@wcstack/router] ${t} contains ${bl} 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 wl(e){return"AbortError"===e?.name}const _l=new WeakMap;function $l(e){for(const t of e.childNodeArray)if(1===t.nodeType){if(t.isConnected){if(qo(t,Bo))continue}else if(null!==zo())continue;vl(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 kl(e,t){try{let n=null;for(const e of t.routes){const r=await e.guardCheck(t);r&&(n=null===n?r:Object.assign({},n,r))}t.data=n,_l.delete(e)}catch(n){if(n instanceof mo){const r=(_l.get(e)??0)+1;return r>10?(_l.delete(e),console.error(`${uo.router}: guard redirect loop — stopped after 10 redirects in a row (the last: ${t.path} → ${n.fallbackPath}). The guards of these routes send each other back and forth.`),!1):(_l.set(e,r),e.connectedCallbackPromise.catch(()=>{}).then(()=>e.replace(n.fallbackPath)).catch(e=>{wl(e)||console.error("Fallback navigation failed:",e)}),!1)}throw n}return!0}async function Sl(e,t,n,r,i=""){const s=ul(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=il(e,s);o||(e.fallbackRoute?o={routes:[e.fallbackRoute],params:{},typedParams:{},path:s,lastPath:r}:po(`${uo.router} No route matched for path: ${s}`)),o.lastPath=r,o.search=i;const l=t.lastRoutes,a=await async function(e,t,n,r){if(!await kl(e,t))return!1;r?.();const i=new Set(t.routes),s=new Set(n),o=()=>{for(const e of n)i.has(e)||dl(e);const e=[];for(const n of t.routes)(e.length>0||!s.has(n)||n.shouldChange(t.params))&&(e.push(n),fl(n,t));let r=!1;for(const t of e){const e=s.has(t);e&&r||ml(t),r||=e,n.length>0&&!e&&$l(t)}};let l;return 0===n.length?o():l=function(e,t,n){const r=function(e){const t=globalThis[gl];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",o),void 0!==l&&await l,!0}(e,o,l,()=>{e.commitNavigation({params:o.params,typedParams:o.typedParams,routeName:o.routes[o.routes.length-1]?.name??"",data:o.data??null,search:i,path:s},!0)});return!!a&&(e.releasePath(),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(nl(e))return e}else for(const t of e.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(nl(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 Nl(){const e=window.navigation;return e?"function"!=typeof e.addEventListener||"function"!=typeof e.removeEventListener?null:e:null}function Cl(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 El(e){return"?"===e?"":e}function Al(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 xl=new WeakMap;function Tl(e,t,n){const r=function(e,t){let n=xl.get(e);return void 0===n&&(n=new Map,xl.set(e,n)),n.has(t)||n.set(t,e.getAttribute(t)),n.get(t)}(e,t);!function(e,t,n){null===n?e.removeAttribute(t):e.setAttribute(t,n)}(e,t,void 0===n?r:null===n?null:String(n))}function Pl(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const Ol=Object.freeze({});class Ml 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"},{name:"leaveConfirm",attribute:"leave-confirm"}],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=Ol;_typedParams=Ol;_searchParams=Ol;_routeName="";_data=null;_hasCommitted=!1;_pathHeld=!1;_leaveChecked=!1;_leaveConfirmed=!1;_listeningUnload=!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 al(e)}_normalizeBasename(e){return cl(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}set basename(e){Tl(this,"basename",e)}get leaveConfirm(){return this.getAttribute("leave-confirm")||null}set leaveConfirm(e){Tl(this,"leave-confirm",e),this._syncBeforeUnload()}_onBeforeUnload=e=>{null!==this.leaveConfirm&&e.preventDefault()};_syncBeforeUnload(){const e=this.isConnected&&null!==this.leaveConfirm&&!Pl();e!==this._listeningUnload&&(this._listeningUnload=e,e?window.addEventListener("beforeunload",this._onBeforeUnload):window.removeEventListener("beforeunload",this._onBeforeUnload))}_confirmLeave(e){const t=this.leaveConfirm;return!(null!==t&&this._hasCommitted&&!this._leaveConfirmed&&!this.isSameMatch(ul(this._normalizePathname(e),this._basename)))||(this._leaveConfirmed=window.confirm(t))}_getOutlet(){const e=this.nextElementSibling;if(e&&e.matches(uo.outlet))return e;!function(e){const t=e.getRootNode();if(t.nodeType!==Node.DOCUMENT_NODE&&t.nodeType!==Node.DOCUMENT_FRAGMENT_NODE)return;const n=uo.router,r=uo.outlet;for(const e of t.querySelectorAll(r))tl.has(e)||e.previousElementSibling?.matches(n)||(tl.add(e),console.warn(`[@wcstack/router] [wcs/router-outlet-misplaced] A <${n}> uses only the element right after it as its outlet, and this page has a <${r}> that no router uses. The router makes an outlet of its own right after itself, so the routes render there and the <${r}> you placed stays empty. Move the <${r}> right after the <${n}>.`,e))}(this);const t=document.createElement(uo.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||po(`${uo.router} has no outlet.`),this._outlet}get template(){return this._template||po(`${uo.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,t=!1){const n=Object.freeze({...e.params}),r=Object.freeze({...e.typedParams}),i=yo(e.search),s=e.data??null,o=this._data!==s,l=!bo(this._params,n),a=this._routeName!==e.routeName,u=!bo(this._searchParams,i),c=this._path!==e.path;o&&(this._data=s),l&&(this._params=n,this._typedParams=r),a&&(this._routeName=e.routeName),u&&(this._searchParams=i),this._path=e.path,this._hasCommitted=!0,this._leaveConfirmed=!1,o&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),l&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),a&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),u&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),this._pathHeld=c&&t,c&&!t&&this._firePathChanged()}releasePath(){this._pathHeld&&(this._pathHeld=!1,this._firePathChanged())}_firePathChanged(){this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:this._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=>{wl(e)||console.error(`${uo.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=>{wl(e)||console.error(`${uo.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=Cl(e),r=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,i=r+El(n.search)+n.hash;if(null!==this.leaveConfirm&&(await Promise.resolve(),!this._confirmLeave(r)))return;const s=Nl();if(s?.navigate){let e;this._leaveChecked=!0;try{e=t?s.navigate(i,{history:"replace"}):s.navigate(i)}finally{this._leaveChecked=!1}await(e?.finished)}else{t?history.replaceState(null,"",i):history.pushState(null,"",i);const e=this._normalizePathname(r),s=this.isSameMatch(ul(e,this._basename));await Sl(this,this.outlet,e,this._path,El(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.defaultPrevented||e.hashChange||null!==e.downloadRequest)return;const t=new URL(e.destination.url),n=this._normalizePathname(t.pathname);if(!this._isOwnPath(n))return;if(!this._leaveChecked&&!1!==e.cancelable&&!this._confirmLeave(n))return void e.preventDefault?.();const r=this.isSameMatch(ul(n,this._basename)),i=r&&("push"===e.navigationType||"replace"===e.navigationType),s=t.search,o=this;e.intercept({handler:async()=>{try{await Sl(o,o.outlet,n,o.path,s)}catch(e){throw console.error(`${uo.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 Sl(this,this.outlet,e,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const e=Pl();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||po(`${uo.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||po(`${uo.router} should have a <template> child element.`);const r=e?this._template.content.cloneNode(!0):null,i=await el(this),s=!e&&this._outlet.hasAttribute(_o);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&&po(`${uo.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(_o);const e=this._outlet.rootNode;for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(i)}await Sl(this,this.outlet,o,this._path,window.location.search||""),(s||null!==zo())&&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(uo.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(ko)){const r=t.slice(15);if(i.has(r)||!n.has(r))return!1;i.set(r,e)}else if(t.startsWith(So)){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(No)){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=ul(e,this._basename);let h=il(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(So)){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()===uo.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(_o);for(const e of h.routes)fl(e,h);return this.outlet.lastRoutes=h.routes,!await kl(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=ul(e,this._basename),n=il(this,t),r=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===r.length&&po(`${uo.router} No route matched for path: ${t}`),!r.some(e=>e.hasGuard)){await Sl(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(e=>{e.placeHolder.data=`${ko}${e.absolutePath}`}),this.outlet.setAttribute(_o,"");for(const e of this.outlet.lastRoutes)e.placeHolder.after(document.createComment(`${So}${e.absolutePath}`))}}_offerInitialContentToBinder(){for(const e of this.outlet.lastRoutes)for(const t of e.childNodeArray)t.nodeType===Node.ELEMENT_NODE&&t.isConnected&&qo(t,Bo)}_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(!Al(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this._syncBeforeUnload(),Pl()){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=Nl();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&&(Nl()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),this._syncBeforeUnload(),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const Ll=["title","rel","target","download","hreflang","lang","dir"];class Il extends HTMLElement{static get observedAttributes(){return["to","match",...Ll]}_childNodeArray=[];_uuid=fo();_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(uo.router);if(e)return this._router=e;const t=this.getRootNode(),n=t.querySelector?.(uo.router);if(n)return this._router=n;po(`${uo.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 al(e)}_joinInternalPath(e,t){const n=cl(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}=Cl(t),s=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);e.href=s+El(r)+i}else try{e.href=new URL(t).toString()}catch{po(`[${uo.link}] Invalid URL in 'to' attribute: ${t}`)}}connectedCallback(){Pl()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const e=this.nextElementSibling;return null!==e&&"A"===e.tagName&&e.hasAttribute($o)?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($o),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-")||Ll.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,Pl())return this._updateActiveState(),void n.setAttribute($o,"");Nl()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!Nl()?.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(){Nl()?.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("match"!==e||t===n){if("to"===e&&t!==n)this._path=n||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(Ll.includes(e)){const t=this._anchorElement;t&&(null===n?t.removeAttribute(e):t.setAttribute(e,n))}}else this._updateActiveState()}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const e=this._normalizePathname(new URL(window.location.href).pathname),{pathname:t}=Cl(this._path),n=this._normalizePathname(this._isInternalTarget(this._path)?""===t?window.location.pathname:this._joinInternalPath(this.router.basename,t):t),r=e===n,i=!r&&"prefix"===this.getAttribute("match")&&e.startsWith(n+"/");this._anchorElement&&(r||i?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current",r?"page":"true")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const jl=[],Rl=new Map;let Hl=!1;const Wl=new WeakMap;class zl 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(),Hl||(this._captureInitialHead(),Hl=!0),jl.push(this),this._reapplyHead()}disconnectedCallback(){const e=jl.indexOf(this);-1!==e&&jl.splice(e,1),this._reapplyHead()}get childElementArray(){return this._initialized||po("Head component is not initialized yet."),this._childElementArray}_getKey(e){const t=Wl.get(e);if(void 0!==t)return t;const n=this._computeKey(e);return Wl.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);Rl.has(e)||Rl.set(e,t.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of jl)for(const n of t._childElementArray)e.add(this._getKey(n));for(const t of Rl.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=jl.length-1;t>=0;t--){const r=jl[t];for(const t of r._childElementArray)if(this._getKey(t)===n){e=t.cloneNode(!0);break}if(e)break}!e&&Rl.has(n)&&(e=Rl.get(n).cloneNode(!0));const r=t.get(n)??null;e?(r?r.replaceWith(e):document.head.appendChild(e),t.set(n,e),qo(e)||vl(e,`<${e.tagName.toLowerCase()}> inside <${uo.head}>`,`<${uo.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(uo.layout)||e.define(uo.layout,Lo),e.get(uo.layoutOutlet)||e.define(uo.layoutOutlet,Vo),e.get(uo.outlet)||e.define(uo.outlet,Io),e.get(uo.route)||e.define(uo.route,Co),e.get(uo.router)||e.define(uo.router,Ml),e.get(uo.link)||e.define(uo.link,Il),e.get(uo.head)||e.define(uo.head,zl)}(void 0);const Ul="data-fetchtarget",Dl={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let Fl=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 ql(e,t){return t.every(t=>"available"===e.availability.get(t))}const Bl=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let Gl=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 Fl("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 ql(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}}(Bl,{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(!ql(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)}}},Kl=!1;function Vl(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest(`[${Ul}]`);if(!n)return;const r=n.getAttribute(Ul);if(!r)return;const i=customElements.get(Dl.fetch),s=document.getElementById(r);if(!(i&&s instanceof i))return;const o=s;o.url&&(e.preventDefault(),o.fetch())}function Jl(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=new WeakMap;function Xl(e,t){let n=Ql.get(e);return void 0===n&&(n=new Map,Ql.set(e,n)),n.has(t)||n.set(t,e.getAttribute(t)),n.get(t)}function Yl(e,t,n){null===n?e.removeAttribute(t):e.setAttribute(t,n)}function Zl(e,t,n){const r=Xl(e,t);Yl(e,t,void 0===n?r:null===n?null:String(n))}const ea=Symbol.for("wcstack.trustedTypes.policy");function ta(){const e=globalThis[ea];return null===e||"object"!=typeof e?null:e}let na,ra=!1;let ia=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Gl.wcBindable,properties:[...Gl.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 Gl(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){Zl(this,"url",e)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(e){Zl(this,"method",e)}get target(){return this.getAttribute("target")}set target(e){Zl(this,"target",e)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(e){Zl(this,"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){!function(e,t,n){const r=Xl(e,t);Yl(e,t,void 0===n?r:n?"":null)}(this,"manual",e)}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(Dl.fetchHeader);for(const n of t)n.hasHeader&&(e[n.headerName]=n.headerValue);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(Dl.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=ta(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(t)}catch(e){if(function(){if(void 0!==na)return na;if(!("trustedTypes"in globalThis))return na=!1,na;try{document.createElement("div").innerHTML="<i></i>",na=!1}catch{na=!0}return na}())return void function(){if(ra)return;ra=!0;const e="function"==typeof ta()?.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(!Jl(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this.style.display="none",Kl||(Kl=!0,document.addEventListener("click",Vl)),!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}},sa=class extends HTMLElement{connectedCallback(){for(const e of["name","value"])if(Object.prototype.hasOwnProperty.call(this,e)){const t=this[e];delete this[e],this[e]=t}this.style.display="none"}get name(){return this.getAttribute("name")??""}set name(e){Zl(this,"name",e)}get value(){return this.getAttribute("value")??""}set value(e){Zl(this,"value",e)}get headerName(){return this.name}get headerValue(){return this.value}get hasHeader(){return""!==this.name&&this.hasAttribute("value")}};class oa extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}class la 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 ia&&(e.loading||(e.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}}!function(e=customElements){e.get(Dl.fetch)||e.define(Dl.fetch,ia),e.get(Dl.fetchHeader)||e.define(Dl.fetchHeader,sa),e.get(Dl.fetchBody)||e.define(Dl.fetchBody,oa),e.get(Dl.infiniteScroll)||e.define(Dl.infiniteScroll,la)}(void 0);const aa="data-storagetarget",ua={storage:"wcs-storage"},ca="wcs-storage:value-changed",ha="wcs-storage:loading-changed",da="wcs-storage:error",fa="wcs-storage:error-info-changed",pa="wcs-storage:trigger-changed";let ma=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:ca,semantics:"state",getter:e=>e.detail},{name:"loading",event:ha,semantics:"state"},{name:"error",event:da,semantics:"state"},{name:"errorInfo",event:fa,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(ha,{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(da,{detail:e,bubbles:!0})))}_commitErrorInfo(e){this._errorInfo=e,this._target.dispatchEvent(new CustomEvent(fa,{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(ca,{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)}},ga=!1;function ya(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest(`[${aa}]`);if(!n)return;const r=n.getAttribute(aa);if(!r)return;const i=customElements.get(ua.storage),s=document.getElementById(r);i&&s instanceof i&&(e.preventDefault(),s.save())}function ba(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 va=new WeakMap;function wa(e,t){let n=va.get(e);return void 0===n&&(n=new Map,va.set(e,n)),n.has(t)||n.set(t,e.getAttribute(t)),n.get(t)}function _a(e,t,n){null===n?e.removeAttribute(t):e.setAttribute(t,n)}function $a(e,t,n){const r=wa(e,t);_a(e,t,void 0===n?r:null===n?null:String(n))}let ka=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...ma.wcBindable,properties:[...ma.wcBindable.properties,{name:"trigger",event:pa,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 ma(this),this._internals=this._initInternals(),this._wireStates({[ha]:e=>({loading:!0===e}),[da]: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){$a(this,"key",e)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(e){$a(this,"type",e)}get value(){return this._core.value}set value(e){void 0!==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){!function(e,t,n){const r=wa(e,t);_a(e,t,void 0===n?r:n?"":null)}(this,"manual",e)}get trigger(){return this._trigger}set trigger(e){if(e){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(pa,{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(!ba(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this.style.display="none",ga||(ga=!0,document.addEventListener("click",ya)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(e=customElements){e.get(ua.storage)||e.define(ua.storage,ka)}(void 0);const Sa="*",Na="vanilla",Ca={loaders:{[Na]:{postfix:".js",loader:async function(e){return(await(import(`${e}`))).default}},[Sa]:Na},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function Ea(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 Aa(e,t,n){let r;if(null===t||t===Sa||""===t){let t=null;const i=[];for(const[e,t]of Object.entries(n)){if(e===Sa)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[Sa],"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 xa=new Set,Ta=new Map;let Pa=new WeakMap;function Oa(e){if(e===globalThis.customElements)return Ta;let t=Pa.get(e);return void 0===t&&(t=new Map,Pa.set(e,t)),t}const Ma=new Map;async function La(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 Ma)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){xa.has(t)||(console.error(`Failed to eager load component '${t}':`,e),xa.add(t))}}function Ia(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 ja(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&&Ma.set(e,t)});const Ra=new WeakSet,Ha=new WeakSet;async function Wa(e,t,n){e.shadowRoot&&(Ra.has(e)||await async function(e,t,n){Ra.add(e),await Fa(e.shadowRoot,t,n)}(e,t,n))}async function za(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=Oa(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=Aa("",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),xa.add(e.name)}}(e,t,i,r);s.set(e.name,l);try{await l}finally{s.delete(e.name)}}async function Ua(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=ja(e);void 0===r.get(i.name)?(Ha.has(e)||(Ha.add(e),r.whenDefined(i.name).then(async()=>{await Wa(e,t,n)})),l.has(i.name)||xa.has(i.name)||(l.add(i.name),o.push(i))):await Wa(e,t,n)}let a=0;for(const e of o)await za(e,t,n,r),a++;return a}async function Da(e,t,n,r){for(;await Ua(e,t,n,r)>0;);}async function Fa(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 Ia(t)}return Ia(globalThis.customElements)}(e);if(null===r)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await Da(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 Da(e,t,n,r)}catch(e){console.error("Failed to lazy load components: "+e)}});return i.observe(e,{childList:!0,subtree:!0}),i}class qa extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),qa._instance)throw new Error(`${Ca.tagNames.autoloader} can only be instantiated once.`);qa._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=Ea(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=Aa(i.key,i.loaderKey,t)}catch(e){throw new Error("Loader redirection is not supported for eager loaded components: "+r)}n.push(La(i,r,s))}await Promise.all(n)}(n,Ca.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 Fa(document,Ca,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,qa._instance===this&&(qa._instance=null)}}!function(e=customElements){e.get(Ca.tagNames.autoloader)||e.define(Ca.tagNames.autoloader,qa)}(void 0);
|
|
1
|
+
var e=class{constructor(e,n,r){this.c=[],this.getter=null,this.ie=null,this.se=!1,this.W=[],this.Q=[],this.pt=null,this.F=-1,this.Y=t,this.De=null,this.Ct=null,this.It=null,this._=null,this.pn=!1,this.mn=!1,this.Wn=!1,this.Z=0,this.mt=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.z=s?[]:null===r?[n]:[...r.z,n],this.h=i}_n(e){this.mt.has(e)||(this.mt.add(e),this.W.push(e),e.Q.push(this))}Io(e){this.mt.delete(e);let t=this.W;t.splice(t.indexOf(e),1)}jo(){this.getter=null,this.ie=null,this.F=-1,this.Y=t,this.W.length=0,this.mt.clear(),this.Q.length=0,this.pt=null,this.De=null,this.Ct=null,this.It=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.ht=new Map,this.Vn=e}jt(e){return this.ht.get(e)}get(t){let n=this.ht.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.ht.set(t,n),i&&i.c.push(n),n}all(){return this.ht.values()}Dt(e){this.ht.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.yt=null,this.N=null,this.he=null,this._=null,this.c=null,this.w=!0,this.l=e,this.y=t,this.$=n}},a=class{constructor(e,t){this.P=null,this.f=[],this.N=null,this.B=null,this.te=!1,this.Lt=!1,this.wt=!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.Mt&&Array.isArray(t)){let e=t.filter(e=>!g.has(e));if(e.length>0)return c.Mt(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.Lo?.(e,t,n)??""}`)}function w(e,t=[]){return c.Bo?.(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.bt=new Set,this.name=e}get size(){return this.bt.size}subscribe(e){return this.bt.add(e),()=>{this.bt.delete(e)}}unsubscribe(e){return this.bt.delete(e)}emit(...e){let t=[];for(let n of this.bt)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="class",T="attr",P=/^\$[1-9]\d{0,2}$/,O=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function M(e){let t=[],n=[],r="",i=null,s=!1,o=-1,l=-1,a=e=>{let i=function(e,t,n){let r=-1===t?e.length:t,i=-1===n?0:n;return e.slice(r-e.slice(0,r).trimStart().length,i+e.slice(i).trimEnd().length)}(r,o,l);(!e||i||s)&&(t.push(i),n.push(function(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:O.test(e)?Number(e):e)}(i,s))),r="",s=!1,o=-1,l=-1};for(let t=0;t<e.length;t++){let n=e[t];i?n===i?i=null:(-1===o&&(o=r.length),r+=n,l=r.length):'"'===n||"'"===n?(i=n,s=!0):","===n?a():r+=n}return null!==i&&_(107,[i,e]),a(!0),{args:t,literals:n}}var L=e=>e.trim();function I(e,t){let n=[],r=null;for(let i=0;i<e.length;i++){let s=e[i];null!==r?s===r&&(r=null):"'"===s||'"'===s?r=s:s===t&&n.push(i)}return n}var j=(e,t)=>I(e,t)[0]??-1;function R(e,t){let n=[],r=0;for(let i of I(e,t))n.push(e.slice(r,i)),r=i+1;return n.push(e.slice(r)),n}function H(e,t,n){let r=j(e,"|");if(-1===r)return[e.trim(),[]];let i=e.slice(r+1).trim(),s=n.get(i);return void 0===s&&(s=function(e,t,n){let r=n??e.join("|");return e.map(e=>{let n=j(e,"("),i=(e=>I(e,")").pop()??-1)(e);if(-1===i&&(i=e.lastIndexOf(")")),-1!==n&&-1===i&&_(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,...M(e.substring(n+1,i))}})}(R(i,"|").map(L),t,e),n.set(i,s)),[e.slice(0,r).trim(),s]}var W=new Map;function D(e){_(1101,[e])}function U(e){let[t,n]=H(e,"output",W);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("**")&&D(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"]],F=["enableMustache","sameValueGuard","enableDirectionalInitialSync"];function q(e){return e.includes("**")&&D(e),e}var B=0;function G(e,t,n){let r=e.get(t);return void 0===r&&e.set(t,r=n()),r}var K=()=>new Set,V=()=>[],J=new WeakMap;function Q(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}function X(e,t){return e===t||e!=e&&t!=t}function Y(e,t,n){let r=e._?.get(t);void 0!==r&&r.delete(n)&&0===r.size&&e._.delete(t)}function Z(e,t){for(let n=0;n<t.length;n++){if(null==e)return;e=e[t[n]]}return e}function ee(e,t){for(;null!==e&&e.l.n>t;)e=e.l.ae;return null!==e&&e.l.n===t?e:null}function te(e,t,n){let r=ee(e,n);return null!==r&&r.l.o===t.h[n]?r:null}var ne=class{constructor(e,t){this.Le=0,this.u=null,this.Be=0,this.vt=new Set,this.et=new Map,this.Un=Symbol("wcs.block"),this.element=null,this.kt=[],this.Me=null,this.qn=[],this.Ht=0,this.X=null,this.oe=new Map,this.ce=new Map,this.We=[],this._e=[],this.Ve=[],this.St=!1,this.hn=!1,this.Ut=new WeakMap,this.j=0,this.qt=0,this.gn=!1,this.Kt=!1,this.zt=!1,this.Fe=0,this.Kn=()=>{this.j=0,this.gn=!1},this.zn=()=>{this.Fe--},this.rp=null,this.rr=null,this.Mo=()=>this.Yt(),this.Wo=(e,t)=>e(this.proxy,...t),this.Yn=[],this.tt=[],this._o={$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=ee(this.u,t);null===n&&_(7,[e]);let r=this.o(e);if(null!==r.getter||r.se)return this.watchIndex(t),n.y===this.read(r,null);let i=this.X;if(null!==i){let e=i.getter,n=r.De??(r.De=[]);if(!n.some(n=>n.getter===e&&n.Xn===t)){n.push({getter:e,Xn:t});let i=e.h[t];(i.Ct??(i.Ct=[])).push({source:r,getter:e})}}return n.y===this.v(r,null)},$eq:(e,t)=>this.eq(e,t),$eqPath:(e,t)=>{let n=this.o(t);return this.eq(e,this.v(n,ee(this.u,n.n)))},$dependOn:e=>{this.resolve(q(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=q(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.A(r,i,e[2])},$postUpdate:e=>{this.resolve(q(e),this.u);let t=this.rp,n=this.rr;"*"===t.s&&null!==n&&(n.$=n.l.P[n.y],J.delete(n.l.P),this.T.Xt(n)),this.bn(t,n),null!==n&&this.Qn(n,t,void 0,n.$,!1),0===t.n&&this.Zn(t,void 0,void 0,!0),this.Gt(t,n,void 0,void 0,!1)}},this.T=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.jt(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(q(t),n.u),n.A(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.F=this.Le++)}for(let e of this.I.all())this.nt(e)}nt(e){e.t.includes("**")&&D(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(P.test(n))e.getter=function(){return this[n]};else{let r=t.split("."),i=r.findIndex((e,t)=>t>0&&e.charCodeAt(0)>=48&&e.charCodeAt(0)<=57);if(i<0||r.indexOf("*",i)>=0)return;e.getter=()=>(this.resolve(t,this.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.A(this.rp,this.rr,r);let i=this.read(e.d,this.u);null==i&&_(4,[t,i]),i[n]=r}}e.Wn=!0,e.n>0&&(e.F=this.Le++)}He(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.G(r),r}no(e){try{this.G(e)}catch(t){this.Jt(t,e.o.t,e.N?.S??null,"for")}}G(e){let t=this.v(e.o,e.ae);if(t===e.P)return;this.oo(e);let n=function(e,t,n){let r=Array.isArray(t)?t:u;if(r===e.P)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[c];)a[c]=i[c],c++;let h=o-1,d=s-1;for(;h>=c&&d>=c&&i[h].$===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[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.$);void 0===r?s.set(n.$,n):Array.isArray(r)?r.push(n):s.set(n.$,[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.y!==e&&(t.y=e,n.Do(t))}return e.f=a,e.P=r,i}(e,t,this);if(null===n)return;if(e.P===t){let n=G(this.Ut,t,V);if(n.push(e),n.length>1)for(let e of n)e.wt=!0}c.Qt?.(this,e,n),(null!==e.N||null!==e.B)&&!e.te&&(e.te=!0,this._e.push(e),this.we());let r=e.o.Ct;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.w&&this.vn(i,s),void 0!==o&&this.vn(i,o))}}Do(e){this.T.Ho(this,e)}Bt(e){e.w=!1;let t=e._;if(null!==t){for(let e of t)Y(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.Ut.get(e.P);void 0!==t&&(t.splice(t.indexOf(e)>>>0,1),e.wt=!1,1===t.length&&(t[0].wt=!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?te(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.He(i,a),h=t[l++];if(h<0)h=te(n,e,o)?.y??-1;else if(r&&c.P===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?Z(this.target,e.z):null===t?void 0:Z(t.$,e.z)}read(e,t){let n=this.X;if(null!==n&&0===n.ye&&this.Gn(e,t,n),null!==e.getter)return this.T.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.vt.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._n(r),0===r.n?e.Z!==n.ue&&(e.Z=n.ue,n.kn.push(e)):e.n>0&&ee(t,Math.min(e.n,r.n))!==ee(n.r,Math.min(e.n,r.n))&&(r.pt??(r.pt=new Set)).add(e)}qo(e,t){for(let n=0;n<this.Ht;n++){let r=this.qn[n];r.getter===e&&r.r===t&&_(701,[e.t])}this.Ht>=128&&_(801,[e.t]);let n=this.Ht++;this.Be++;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=++B,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.Be--,this.Ht--,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.Y: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.W.length>0)&&(null===n.getter||n.Wn&&n.F<0)&&null===n._){n.mn=!0,this.I.Dt(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.It??(r.It=[]);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:P.test(e)?+e.slice(1):0;return(n<1||n>128)&&_(1001,[e]),this.watchIndex(n),ee(this.u,n)?.y}let n=this._o[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 X(this.read(n,r),t);let i=this.X;return null!==i&&0===i.ye&&this.Yo(n,t,i),X(this.v(n,null),t)}Yo(e,t,n){let r=n.getter,i=n.r,s=null===i?this.Yn:i._??(i._=[]);for(let i=0;i<s.length;i++){let o=s[i];if(o.sub.getter===r&&o.source===e){if(X(o.key,t))return void(o.ue=n.ue);o.ue!==n.ue&&(Y(e,o.key,o.sub),s.splice(i--,1))}}let o={getter:r,r:i};G(e._??=new Map,t,K).add(o),s.push({source:e,key:t,sub:o,ue:n.ue})}Zn(e,t,n,r){this.Zt(e,i=>{let s=i._;if(null===s&&null===i.De)return;let o=i===e?[]:i.t.slice(e.t.length+1).split("."),l=Z(t,o),a=Z(n,o);if(null!==i.De&&this.Xo(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.w?this.T.be(this,n.getter,n.r):Y(i,e,n)}})}A(e,t,n,r=!1,i=!1){if(this.Be>0&&_(8),i||this.Fe>0?this.Kt=!0:this.zt=!0,c.Oe?.(this,e,t,n,i))return;if(null!==e.ie){try{this.Sn(e.ie,t,[n])}finally{this.Gt(e,t,void 0,void 0,!1,i)}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.P[e.y]=n,J.delete(e.l.P),e.$=n,this.T.Xt(e)}else{let r=1===e.z.length?0===e.n?this.target:t.$: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.Gt(e,t,s,n,!0,i)}}so(e){return(this.Ut.get(e.P)??[]).filter(t=>t.P===e.P&&(null===t.ae||t.ae.w))}Qn(e,t,r,i,s=!0){let o=e.l,l=t.t.slice(o.o.t.length+2),a=""!==l&&function(e){let t=J.get(e);if(void 0===t){let n=new Set;J.set(e,t=e.some(e=>Object(e)===e&&(n.has(e)||!n.add(e))))}return t}(o.P);if(!a&&!o.wt&&null===o.o.getter&&!o.o.W.length)return;let u=e.$,c=(t,n)=>{if(void 0===n||n===e)return;let o=this.o(`${t.o.t}.*${l}`,!0);""===l&&(n.$=i,this.T.Xt(n)),s?this.En(o,n):this.bn(o,n),this.Gt(o,n,r,i,s)};for(let t of this.so(o))if(c(t,t.f[e.y]),a)for(let n of t.f)n.$===u&&n.y!==e.y&&c(t,n);if(""===l)return;let h=new Set([o.P]),d=e=>Array.isArray(e)&&e.includes(u),f=(e,t)=>{if(!h.has(e)&&h.add(e))for(let t of this.Ut.get(e)??[])for(let e of t.f)e.$===u&&c(t,e);for(let r of t){let t=r.Y,i=t===n;i&&(t=this.oe.get(r)?.P),(i||d(t))&&!h.has(r.W)&&h.add(r.W)&&(!i&&t!==e&&this.T.be(this,r,null),f(t,r.W))}},p=e=>{for(let t of e.Q)if(!h.has(t)&&h.add(t))if(null!==t.getter)p(t);else if(!t.se){let e=this.rt(t,null);d(e)&&f(e,t.W)}};null!==o.o.getter?p(o.o):f(o.P,o.o.W)}bn(e,t){this.Go(e,t,e=>{this.G(e);for(let t of e.wt?this.so(e):[e]){let e=this.o(`${t.o.t}.*`);for(let n of t.f)this.Et(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.G(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)}Xo(e,t,n,r){for(let{getter:i,Xn:s}of e.De)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.T.be(this,e,t):this.en(t,e,t=>this.T.be(this,e,t))}Gt(e,t,n,r,i,s){c.ve?.(this,e,t,n,r,i,s),this.Ue(e,t)}Ue(e,t){this.T.Jo(this,e,t),this.we()}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.w&&o.Qo(e,t))return}}),n}reset(e){let t=this.target,n=this.vt;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.tn(t);for(let e of this.oe.values())this.co(e);this.Me=null;try{this.Yt()}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)(!F.includes(e)||"boolean"!=typeof n[e])&&_(44,["$behavior",e]);let[r,i,s]=F.map(e=>n[e]??!0);void 0!==this.target&&(r!==this.Wt||i!==this._t||s!==this.Vt)&&_(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.Wo);this.Wt=r,this._t=i,this.Vt=s,c.de?.(this,e),this.target=e,this.Le=0;for(let e of this.I.all())e.jo();this.Yn.length=0,this.to(e),this.commands=o,this.Ae=l}co(e){this.no(e);let t=this.o(`${e.o.t}.*`);for(let n of e.f)if(n.yt=null,n._=null,this.Et(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.y);return t}Zo(e,t,n){let r=this.Ae.get(e);void 0===r&&_(1301,[e],e,this.Ae.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}}Et(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.Ve.push(t))}if(null===t)return void this.Zt(e,e=>{let t=this.ce.get(e);if(void 0!==t)for(let e of t)this.tn(e)});let n=t.he;if(null!==n)for(let t=0;t<n.length;t++)n[t].o.ee(e)&&this.tn(n[t]);let r=t.N;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.Zt(e,e=>{let r=e.W;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.pt&&s.pt.has(e))this.nn(s.h[s.n],e=>this.it(s,e,n));else if(s.n<=e.n){let e=ee(t,s.n);null!==e&&this.it(s,e,n)}else this.en(t,s,e=>this.it(s,e,n))}})}it(e,t,n){n(e,t)&&(c.ke?.(this,e,t),this.Et(e,t),this.Nn(e,t,n))}Zt(e,t){t(e);let n=e.c;for(let e=0;e<n.length;e++)this.Zt(n[e],t)}nn(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.nn(e.h[e.n],n=>{let r=n.c?.get(e);void 0!==r&&t(r)})}en(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.en(e,t,n)}nr(e){let t=e.r;null===t?G(this.ce,e.o,K).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.w&&null!==n&&n.splice(n.indexOf(e)>>>0,1)}tn(e){e.te||(e.te=!0,this.We.push(e),this.we())}we(){this.St||(this.St=!0,queueMicrotask(this.Mo))}Rn(){for(let e of this.We)e.te=!1;for(let e of this._e)e.te=!1;for(let e of this.Ve)e.Lt=!1;this.We=[],this._e=[],this.Ve=[],this.T.vt(this)}fo(e,t){let n=[...new Set([...this.We,...this._e,...this.Ve].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()}Yt(){this.St=!1;let e=this.qt;this.qt=0;let t=0;if(!this.Kt||this.zt?this.Kn():e>0?t=e:1===(t=++this.j)&&setTimeout(this.Kn,0),this.Kt=this.zt=!1,t>100)101===t?this.fo(41,100):this.Rn();else{this.hn=!0;try{for(let e=0;this.We.length>0||this._e.length>0||this.Ve.length>0;e++){if(e>=32){this.gn?this.Rn():this.fo(11,32),this.gn=!0;break}let n=this.Ve;if(n.length>0){this.Ve=[];for(let e of n)e.Lt=!1,this.no(e)}let r=this._e,i=this.We;this._e=[],this.We=[];let s=()=>{for(let e of r){e.te=!1;for(let t of[e.N,...e.B??[]])if(null!==t&&t.w)try{t.$t()}catch(n){this.Jt(n,e.o.t,t.S,"for")}}for(let e=0;e<2;e++)for(let t=0;t<i.length;t++){let n=i[t];!n.te||null===n.j==(0===e)||(n.te=!1,(null===n.Pn||n.Pn.w)&&this.qe(n))}this.hn||(this.Ke(),this.St&&(this.qt=t+1))},o=r.length>0||i.some(e=>null!==e.j)?E("state",s):s();void 0!==o&&o.then(void 0,e=>console.error(e))}}finally{this.hn=!1}this.Kt=this.zt=!1,this.Ke(),c.Ce?.(this),this.zo(),e>0&&this.St&&(this.qt=t+1)}}Nt(e,t){this.kt.push([e,t])}Jt(e,t,n,r){this.Nt(e,{o:{t:t},a:n,on:()=>r})}qe(e){try{e.apply()}catch(t){return void this.kt.push([t,e])}null!==this.Me&&this.po(e.o,e.r)}po(e,t){let n=G(this.Me,e.t,V);null!==t&&n.push(this.H(t))}$n(){this.Me="function"==typeof this.target.$renderedCallback?new Map:null}Ke(){let e=this.Me;if(null!==e&&e.size>0){this.Me=new Map;let t,n=[...e.keys()],r={};for(let[t,n]of e)n.length>0&&(r[t]=n);this.Fe++;try{t=this.Se("$renderedCallback",[n,r])}catch(e){console.error(e)}Q(t)?t.then(this.zn,e=>{this.zn(),console.error(e)}):this.Fe--}if(0===this.kt.length)return;let t=this.kt;this.kt=[];let n=this.target.$errorCallback;for(let[r,i]of t){c.ze?.(this,r,i);let t=i.o.t,s=i.on();if("function"==typeof n)try{let e=this.Se("$errorCallback",[r,{path:t,bindingType:s,node:i.a}]);Q(e)&&e.then(void 0,e=>console.error(e))}catch(e){console.error(e)}else console.error(`[@wcstack/state] ${w(12,i.name?[s,t,i.name,i.i]:[s,t])}`,r,i.a)}}Se(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.He(o,l),u=t=>{r.push(t.y),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=te(t,n,e);if(null===i)break;r.push(i.y)}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.Be>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.A(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])}},re={bindAttributeName:"data-wcs",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:typeof document<"u"&&document.documentElement?.lang||"en"},ie=new Map,se=new Set(["if","elseif","else","for"]),oe=new Set([A,"if","elseif","for","..."]),le=new Set([x,T,"style","command",C,"state"]);function ae(e){let t=function(e){return R(e,";")}(e).map(L).filter(e=>e.length>0).map(e=>{let t=j(e,":");-1===t&&_(101,[e]);let n=e.slice(0,t).trim(),r=e.slice(t+1).trim(),i=n.split("#")[0].split("|")[0].trim();if(oe.has(i)){let t;return i!==n&&_(102,[e,i]),i===A?(r.length>0&&_(103,[e]),t={Qe:"#else",Ze:[]}):"..."===i?(0===r.length&&_(104,[e]),t=U(r),t.Ze.length>0&&_(105,[e])):(t=U(r),"for"===i&&t.Ze.length>0&&_(121,[e])),{Ee:i,$e:[i],rn:[],D:[],...t,b:"..."===i?"spread":i}}(i===x||i===T)&&_(122,[e,i]);let s=U(r),o=function(e){let[t,n]=H(e,"input",ie),r=t.split("#").map(L);r.length>2&&_(115,[t]);let[i,s]=r,o=i.split(".").map(L);return!(o.length>1&&""===o[0])&&(0===i.length||o.some(e=>0===e.length))&&_(116,[e]),{Ee:i,$e:o,rn:s?s.split(",").map(L):[],D:n}}(n),[l]=o.$e;if(""===l&&o.$e.length>1){let e=o.$e.slice(1);return(e.includes("")||le.has(e[0]))&&_(106,[n]),{...o,Ee:e.join("."),$e:e,...s,b:"prop"}}return{...o,...s,b:"radio"===i||"checkbox"===i?i:l===C||l.startsWith("on")?"event":"prop"}});return t.length>1&&t.some(e=>se.has(e.b))&&_(201,[e]),t}var ue=["toFixed","locale","upper","lower","capitalize","trim","slice","padStart","padEnd","repeat","reverse","truncate","join","round","floor","ceil","percent","unit","date","time","datetime","ymd","hms","add","sub","mul","div","mod","abs","clamp","int","float","defaults","coalesce","number","string","nullIfEmpty","currency"],ce=new Map,he=new Map;function de(e){for(let t of Object.keys(e))ce.set(t,{...e[t]});he.clear()}function fe(e){return ce.has(e)}function pe(e){_(26,[e])}function me(e){_(27,[e])}function ge(e,t){_(28,[e,t])}function ye(e,t){_(29,[e,t])}function be(e){return!(!e||isNaN(Number(e)))}function ve(e,t){return be(e)||me(t),Number(e)}function we(e,t,n){return ve(e?.[t]??pe(n),n)}function _e(e,t){return void 0!==t&&t.length>0?t[0]:e}var $e=(e,t)=>({factory:n=>{let r=we(n,0,e);return n=>("number"!=typeof n&&ge(e,n),t(n,r))},arity:[1,1]}),ke={eq:{factory:(e,t)=>{let n=e?.[0]??pe("eq"),r=_e(n,t);return e=>"number"==typeof e?"string"!=typeof r?e===r:(be(n)||me("eq"),e===Number(n)):"string"==typeof e?e===n:e===r},arity:[1,1]},ne:{factory:(e,t)=>{let n=e?.[0]??pe("ne"),r=_e(n,t);return e=>"number"==typeof e?"string"!=typeof r?e!==r:(be(n)||me("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==r},arity:[1,1]},not:{factory:()=>e=>!e,arity:[0,0]},lt:$e("lt",(e,t)=>e<t),le:$e("le",(e,t)=>e<=t),gt:$e("gt",(e,t)=>e>t),ge:$e("ge",(e,t)=>e>=t),falsy:{factory:()=>e=>!e,arity:[0,0]},truthy:{factory:()=>e=>!!e,arity:[0,0]},boolean:{factory:()=>e=>!!e,arity:[0,0]}},Se=!1;function Ne(e,t){if(null!==e)for(let n=0;n<e.length;n++)t=e[n](t);return t}function Ee(e){return 0===e.length?null:(Se||(Se=!0,de(ke)),e.map(e=>function(e,t,n){let r=`${e}${function(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}(t,n)}`,i=he.get(r);if(typeof i<"u")return i;let s=ce.get(e);void 0===s&&function(e,t){ue.includes(e)&&v(`[wcs/filter-unknown] filter not found: ${e}. "${e}" is in the formats add-on — install it with installFeatures([formats]) from "@wcstack/state/features/formats".`,e,t),_(501,[e],e,t)}(e,ce.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 he.set(r,a),a}(e.Hn,e.args,e.literals)))}var Ae=Symbol.for("wcstack.trustedTypes.policy");function Ce(){let e=globalThis[Ae];return null!==e&&"object"==typeof e?e:null}function xe(e){return"innerHTML"===e||"outerHTML"===e||"srcdoc"===e}function Te(e){if(globalThis.trustedTypes?.isHTML(e))return e;let t=null==e?"":String(e),n=Ce(),r=n?.createHTML;return"function"==typeof r?r.call(n,t):t}var Pe=Symbol.for("wcstack.state.view-transition-naming"),Oe=new WeakSet;function Me(){let e=N("state");return null!==e&&"auto"===e.naming?e.namingLimit:-1}var Le=new WeakMap,Ie=e=>e.customElementRegistry??customElements;function je(e,t,n,r,i,s=!1){let o=n.localName;if(!o.includes("-"))return i(null);let l=Ie(n);if(!s&&!n.isConnected&&void 0===l.get(o)&&"customElementRegistry"in n)return void queueMicrotask(()=>je(e,t,n,r,i,!0));let a=()=>{let e=l.get(o);l.upgrade(n),i(e?function(e){if(Le.has(e))return Le.get(e);let t=e.wcBindable,n=null;if(null!==t&&"object"==typeof t&&"wc-bindable"===t.protocol&&Number.isInteger(t.version)&&t.version>=1){n={properties:new Map,inputs:new Set,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.add(e.name);for(let e of t.commands??[])null!==e&&"object"==typeof e&&"string"==typeof e.name&&n.commands.add(e.name)}return Le.set(e,n),n}(e):null)};if(!s&&void 0!==l.get(o))return a();null!==r&&!r.w||function(e,t,n){let r=n;null!==t&&(t.xt??=[]).push(()=>{r=null}),e.then(()=>r?.())}(l.whenDefined(o),r,()=>{try{a()}catch(r){ze(e,r,t,n)}e.we()})}function Re(e,t,n,r,i=t.o,s,o,l){let a=l.properties.get(r)??null,u=l.inputs.has(r),h=e.Vt;h&&null===a&&!u&&_(38,[r]);let d=t.U;(null===a?"element"===d||"auto"===d:!u&&("state"===d||"auto"===d))&&_(39,[d,r]),"connect"===t.G&&null===a&&_(40,[r]);let f=h&&null!==a&&!u,p=new Be(e,De,n,r,i,s,o,t.x,void 0);p.D=t.D,Ze(e,p,!f),null!==a&&!t.ro&&n.addEventListener(a.event,t=>{let i;null!==a.getter?i=a.getter(t):(i=t.detail,a.ho||c.detail?.(n,r,i)),(!p.Tn||!Object.is(i,p.value))&&(i=Ne(p.D,i),null===p.x&&(p.value=i),e.A(p.o,p.r,i,a.ho,!0))});let m=d??(f?"element":"state");if("state"===m)f||e.qe(p);else if("element"===m||"auto"===m){let i=()=>{if(null!==o&&!o.w)return;if("auto"===m&&void 0!==e.v(p.o,p.r))return void(f||e.qe(p));let t=n[r];null===p.x&&(p.value=t),e.A(p.o,p.r,t,!1,!0)};"connect"!==t.G||n.isConnected?i():Promise.resolve().then(i)}return p}function He(e,t,n){_(e,[t.localName,n])}var We=new Set(["click","dblclick","input","change","submit","keydown","keyup","mousedown","mouseup","pointerdown","pointerup"]),De=11,Ue=["text","prop","prop","prop","prop","event","for","if","prop","radio","checkbox","prop","prop","event","spread"],ze=(e,t,n,r)=>e.Jt(t,n.o?.t??n.Rt,r,Ue[n.i]),Fe=Symbol();function qe(e,t,n){let r=t.U;return null===r||"state"===r||"auto"===r&&void 0!==e.v(t.o,n)?t.q:Fe}var Be=class{constructor(e,t,n,r,i,s,o,l,a,u=null){this.te=!1,this.D=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.x=l,this.value=a,this.j=u}on(){return Ue[this.i]}apply(){if(null!==this.j)return void this.j.$t();let e=Ne(this.x,this.engine.read(this.o,this.r));if(e===this.value&&9!==this.i&&("object"!=typeof e||null===e||this.i===De||8===this.i||xe(this.name)))return;if(this.value===Fe)return void(this.value=e);let t=this.a;if(this.i!==De)9===this.i?t.checked=void 0!==e&&this.sn()===e:10===this.i?t.checked=Array.isArray(e)&&e.includes(this.sn()):Ke(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}}}sn(){return Ne(this.D,this.a.value)}ir(){let e,t=this.a,n=this.engine;if(9===this.i){if(!t.checked)return;e=this.sn()}else if(10===this.i){let r=this.sn(),i=n.v(this.o,this.r),s=Array.isArray(i)?i:[],o=s.includes(r);if(t.checked?o:!o)return;e=o?s.filter(e=>e!==r):[...s,r]}else e=Ne(this.D,t[this.name]),this.value=NaN;n.A(this.o,this.r,e,!1,!0)}},Ge=e=>"textContent"===e||"innerText"===e||"innerHTML"===e;function Ke(e,t,n,r){switch(e){case 0:return void(t.data=null==r?"":String(r));case 1:return void(Ge(n)?t[n]="innerHTML"===n?Te(r):null==r?"":String(r):xe(n)?null==r&&"srcdoc"===n?t.removeAttribute(n):void 0!==r&&(t[n]=Te(r)):void 0!==r&&(t[n]!==r&&!("value"===n&&t.value===String(r))&&(t[n]=r),("value"===n||"selectedIndex"===n)&&"select"===t.localName&&(t[Ve]=[n,r])));case 8:return void(t.innerHTML=Te(r));case 2:return null!=r&&"boolean"!=typeof r&&_(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 Ve=Symbol();function Je(e){let t="optgroup"===e.localName?e.parentNode:e,n=t?.[Ve];void 0!==n&&(t[n[0]]=n[1])}var Qe=class{constructor(e,t,n,r){this.w=!0,this.he=null,this.c=null,this.xt=null,this.Fn=null,this.r=e,this.at=t,this.L=n,this.O=r}Qo(e,t){let n=t.target,r=this.O,i=[],s=null;for(let t of r.Ae){if(t.name!==e)continue;let o=r.On[t.a],l=at(null===this.L?this.at: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.at:this.L[this.L.length-1]}xe(){let e=this.Fn;return(null===e?null:e.Cn(this.at))??this.at}insertBefore(e,t){let n=this.s;for(let r=this.xe();;){let i=r.nextSibling;if(e.insertBefore(r,t),r===n)return;r=i}}wo(){null===this.L?this.at.remove():ut(this.xe(),this.s)}Re(e){if(this.w=!1,null!==this.xt)for(let e of this.xt)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.Re()}},Xe=class extends Qe{constructor(e,t,n,r){super(e,t,n,r),this.bo=0,this.V=null,this.fe=0===r.Ye.length?null:new Array(2*r.Ye.length)}vo(e,t){let n=this.V??=new Array(this.O.Ye.length),r=n[t];if(void 0===r){let i=this.O.Ye[t],s=this.fe;r=n[t]=new Be(e,i.i,s[2*t],i.name,i.o,this.r,this,i.x,s[2*t+1])}return r}uo(e,t){let n=this.O.Ye;for(let r=0;r<n.length;r++)n[r].o.ee(t)&&e.tn(this.vo(e,r))}Re(e){let t=this.r;t.N===this&&(t.N=null),super.Re(e)}};function Ye(e,t,n,r){let i=ee(n,t.n);try{return e.He(i,t)}catch(n){return e.Jt(n,t.t,r,"for"),null===i?e.oe.get(t):i.c.get(t)}}function Ze(e,t,n){n&&e.nr(t);let r=t.Pn;null!==r&&(r.he??=[]).push(t)}var et=null;function tt(){let e=et;return et=null,e}var nt=-1;function rt(e,t,n,r,i=null){let s,o=t.On,l=t.build,a=t.ko,u=null,h=c.Ie?.(t,null===r?i:r.S,null!==r),d=!h&&t.In,f=h?document.createDocumentFragment():(d?t.root:t.ln).cloneNode(!0);if(!h)for(let e=0;e<l.length;e++){let t=l[e];a[t]=at(f,o[t],d?1:0)}d?s=f:(u=h||[...f.childNodes],s=u[0]);let p,m=null;if(null!==r?(p=m=new Xe(n,s,u,t),null===r.map?n.N=m:r.map.set(n,m)):p=new Qe(n,s,u,t),nt>=0&&function(e,t,n,r){let i=null;if(null===t)i=1===e.nodeType?e:null;else for(let e=0;e<t.length&&null===i;e++)1===t[e].nodeType&&(i=t[e]);let s=i?.style;if(null===i||void 0===s||Oe.has(i))return;let o=globalThis[Pe]??={counter:0,assigned:0,warned:!1};o.assigned>=r?o.warned||(o.warned=!0,console.warn(`[@wcstack/state] ${w(25,[r])}`)):(Oe.add(i),o.assigned++,s.setProperty("view-transition-name",`wcs-${n}-${++o.counter}`),s.setProperty("view-transition-class",`wcs-${n}`))}(s,u,null!==r?"row":"branch",nt),t.Ae.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.Me,b=t.lr?a.slice(0,o.length):a,v=null===m?null:m.fe;if(null!==v){let e=t.Ye;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.F;if(l>=0&&null!==v){let r=m.V?.[l];if(void 0!==r){r.te=!1,e.qe(r);continue}try{let t=Ne(i.x,e.read(i.o,n));t!==i.q&&(Ke(i.i,o,i.name,t),v[2*l+1]=t),null!==y&&e.po(i.o,n)}catch(t){e.Nt(t,m.vo(e,l))}continue}switch(i.i){case 6:{let t=new lt(e,i.O,Ye(e,i.o,n,o),o);(p.c??=[]).push(t),o===s&&(p.Fn=t),t.$t();break}case 7:{let t=st(e,i.K.map(e=>({O:e.O,o:e.o,x:e.x,S:b[e.a]})),n,p);(p.c??=[]).push(t),o===s&&(p.Fn=t);break}default:try{it(e,i,o,n,p)}catch(t){ze(e,t,i,o)}}}return et=p,f}function it(e,t,n,r,i){let s=n;switch(t.i){case 5:return void function(e,t,n,r,i){let s=n.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.Ne&&t.addEventListener(n.name,e=>e.bubbles||o(e))}else t.addEventListener(n.name,o),n.yo&&null!==i&&(i.xt??=[]).push(()=>t.removeEventListener(n.name,o))}(e,n,t,r,i);case 12:return void je(e,t,s,i,n=>function(e,t,n,r,i){let s=t.name,o=e.command(t.Rt.slice(9)),l=null===i?c.or?.(n,s):null;l||(null===i&&He(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.xt??=[]).push(u)}(e,t,s,i,n));case 13:return void je(e,t,s,i,n=>function(e,t,n,r,i){let s=t.name;null===i&&He(1202,n,`eventToken.${s}`);let o=i.properties.get(s);void 0===o&&_(1204,[n.localName,s]);let l=t.Rt;n.addEventListener(o.event,n=>{t.Pt&&n.preventDefault(),t.Tt&&n.stopPropagation();try{e.Zo(l,n,r)}catch(e){console.error(e)}})}(e,t,s,r,n))}let o=t.o,l=ee(r,o.n);if(14===t.i)return void je(e,t,s,i,n=>function(e,t,n,r,i,s){null===s&&He(1501,n,`"...: ${t.o.t}"`);let o=new Set([...s.properties.keys(),...s.inputs]);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;Re(e,{...t,U:null,G:null},n,l,o,a,i,s)}}(e,t,s,l,i,n));if(t.Ne&&1===t.i)return void je(e,t,s,i,n=>function(e,t,n,r,i,s){if(null!==s)return void Re(e,t,n,t.name,t.o,r,i,s);let o=new Be(e,1,n,t.name,t.o,r,i,t.x,qe(e,t,r));o.D=t.D,!c.ar?.(o,t.ro)&&(Ze(e,o,!0),e.qe(o))}(e,t,s,l,i,n));let a=new Be(e,t.i,n,t.name,o,l,i,t.x,qe(e,t,l));a.D=t.D,Ze(e,a,!0),e.qe(a),null!==t.At&&n.addEventListener(t.At,()=>a.ir())}function st(e,t,n,r){let i=new ot(e,t,n),s=null;for(let o of t){if(null===o.o)continue;let t=o.o,l=new Be(e,7,o.S,"if",t,ee(n,t.n),r,null,void 0,i);Ze(e,l,!0),null===r&&i.ce.push(l),s??=l}return e.qe(s),i}var ot=class{constructor(e,t,n){this.w=!0,this.C=null,this.y=-1,this.ce=[],this.engine=e,this.K=t,this.r=n}Cn(e){return null!==this.C&&this.K[this.y].S===e?this.C.xe():null}$t(){let e=this.engine,t=-1;for(let n=0;n<this.K.length;n++){let r=this.K[n];if(null===r.o||Ne(r.x,e.read(r.o,ee(this.r,r.o.n)))){t=n;break}}if(t!==this.y&&(nt=Me(),null!==this.C&&(this.C.wo(),this.C.Re(e),this.C=null),this.y=t,t>=0)){let n=this.K[t],r=rt(e,n.O,this.r,null,n.S);this.C=tt();let i=n.S.parentNode;i.insertBefore(r,n.S),Je(i)}}Re(){this.w=!1;for(let e of this.ce)this.engine.xn(e);null!==this.C&&this.C.Re(this.engine)}},lt=class{constructor(e,t,n,r){this.w=!0,this.Pe=[],this.engine=e,this.O=t,this.l=n,this.S=r,null===n.N?(n.N=this,this.map=null):((n.B??=[]).push(this),this.map=new Map)}Cn(e){return 0===this.Pe.length?null:this.Pe[0].xe()}Ft(e){return null===this.map?e.N:this.map.get(e)??null}Dt(e){let t=this.map;null!==t&&t.get(e.r)===e&&t.delete(e.r),e.Re(this.engine)}$t(){let e=this.engine,t=this.l.f,n=this.Pe;nt=Me();let r=t.length,i=n.length,s=this.S,o=s.parentNode;if(0===r){if(i>0){let e=n[0].xe(),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):ut(e,t);for(let e=0;e<i;e++)this.Dt(n[e])}return void(this.Pe=[])}let l=new Array(r),a=0;for(;a<r&&a<i&&this.Ft(t[a])===n[a];)l[a]=n[a],a++;let u=i-1,c=r-1;for(;u>=a&&c>=a&&this.Ft(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.w&&this.Ft(r)===t?t.bo=e:(t.wo(),this.Dt(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.Ft(t[a+e]);null!==n&&n.w?(u[e]=n.bo,h=!0):u[e]=-1}let d=c+1<r?l[c+1].xe():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.Ft(n);null!==u&&u.w?0===r[s]&&u.insertBefore(o,i):(o.insertBefore(rt(e,this.O,n,this),i),u=tt()),l[a+s]=u,i=u.xe()}}else{let n=document.createDocumentFragment();for(let r=a;r<=c;r++)n.appendChild(rt(e,this.O,t[r],this)),l[r]=tt();o.insertBefore(n,d)}}this.Pe=l,Je(o)}Re(){this.w=!1;let e=this.l;if(e.N===this)e.N=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.Pe)e.Re(this.engine);this.map?.clear()}};function at(e,t,n){for(;n<t.length;n++){e=e.firstChild;for(let r=t[n];r>0;r--)e=e.nextSibling}return e}function ut(e,t){for(let n,r=e;r!==t;r=n)n=r.nextSibling,r.remove();t.remove()}var ct=()=>re.bindAttributeName;function ht(){return{a:0,i:1,name:"",o:null,x:null,q:t,An:null,O:null,K:null,D:null,At:null,Ne:!1,U:null,G:null,ro:!1,Pt:!1,Tt:!1,Rt:null,go:null,F:-1,et:!1,yo:!1}}var dt=["state","element","auto","none"],ft=["call","connect"],pt="$command.";function mt(e,t,n){P.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 gt=e=>1===e.i&&("outerHTML"===e.name||"outerText"===e.name),yt=e=>8===e.i||gt(e)||1===e.i&&Ge(e.name);function bt(e){_(202,[e])}function vt(e,t,n,r,i){let s=ae(t).map(t=>function(e,t,n,r,i){let s=function(e,t){let n=t.find(e=>e.startsWith("on")),r=null,i=null;for(let n of t){let t=n.indexOf("=");if(t<0)continue;e.Vt||_(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?dt:ft).includes(o)||_(35,[s,o]),l?r=o:i=o}return{ro:t.includes("ro"),Pt:t.includes("prevent"),Tt:t.includes("stop"),event:n?n.slice(2):null,U:r,G:i}}(e,t.rn),o=r.localName.includes("-"),l=t.$e,a=t.Qe;if("event"===t.b){if(null!==s.U&&"none"!==s.U&&_(36),"eventToken"===l[0])return{...ht(),a:i,i:13,name:l.slice(1).join("."),Rt:a,Ne:o,Pt:s.Pt,Tt:s.Tt};let n=a.startsWith(pt)?a.slice(9):null,{Pt:r,Tt:u}=s,c=t.Ee.slice(2),h=t.rn.includes("direct"),d=!h&&We.has(c);return d&&e.ao(c),{...ht(),a:i,i:5,name:c,et:d,Ne: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);Q(n)&&n.then(void 0,e=>console.error(e))}}catch(e){console.error(e)}}}}if("spread"===t.b)return{...ht(),a:i,i:14,o:mt(e,a,n),Ne:o};if("command"===l[0]&&l.length>1)return a.startsWith(pt)||_(1201,[t.Ee,a]),{...ht(),a:i,i:12,name:l.slice(1).join("."),Rt:a,Ne:o};let u=mt(e,a,n),c={...ht(),a:i,i:1,name:t.Ee,o:u,x:Ee(t.Ze),D:Ee(t.D),ro:s.ro,U:s.U,G:s.G};if("radio"===t.b||"checkbox"===t.b)return("element"===s.U||"auto"===s.U)&&_(37,[t.b,s.U]),c.i="radio"===t.b?9:10,s.ro||(c.At=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.Ee?(c.i=8,c):(c.name="text"===t.Ee?"textContent":t.Ee,c.Ne=o&&!xe(c.name),!o&&!s.ro&&function(e,t){let n=e.localName;if("input"===n){let n=(e.getAttribute("type")||"text").toLowerCase();return"button"!==n&&(("radio"===n||"checkbox"===n)&&"checked"===t||"value"===t||"valueAsNumber"===t||"valueAsDate"===t)}return("select"===n||"textarea"===n)&&"value"===t}(r,c.name)&&(c.At=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 wt=/\{\{([\s\S]+?)\}\}/g;function _t(e){let t=e.data,n=[],r=0;wt.lastIndex=0;for(let i=wt.exec(t);null!==i;i=wt.exec(t)){let s=wt.lastIndex-i[0].length;s>r&&e.before(t.slice(r,s));let o=e.ownerDocument.createTextNode("");e.before(o),n.push({a:o,cr:i[1].trim()}),r=wt.lastIndex}return 0===n.length||(r<t.length&&e.before(t.slice(r)),e.remove()),n}function $t(e,t,n,r){let i=function(e){return{Ee:"textContent",$e:["textContent"],rn:[],D:[],...U(e),b:"text"}}(t);return{...ht(),a:r,i:0,o:mt(e,i.Qe,n),x:Ee(i.Ze),q:""}}function kt(e){let t=e.getAttribute(ct());if(null===t)return null;let n=ae(t)[0];return void 0===n||"for"!==n.b&&"if"!==n.b&&"elseif"!==n.b&&"else"!==n.b?null:n}var St=(e,t)=>0===e?re.commentIfPrefix:null===t.o?re.commentElsePrefix:re.commentElseIfPrefix;function Nt(e,t,n){let r=(t,r)=>({el:t,o:"else"===r.b?null:mt(e,r.Qe,n),x:"else"===r.b?null:Ee(r.Ze)}),i=[r(t,kt(t))];for(let e=t.nextSibling;null!==e;e=e.nextSibling){if(3===e.nodeType&&""===e.data.trim()||8===e.nodeType)continue;if(1!==e.nodeType||"template"!==e.localName)break;let t=kt(e);if(null===t||"elseif"!==t.b&&"else"!==t.b||(i.push(r(e,t)),"else"===t.b))break}return i}var Et=new WeakSet;function At(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(t.hasAttribute(ct()+"-ignore"))continue;if(r){if("script"===l||"style"===l||Et.has(t))continue;if(Et.add(t),l===re.tagNames.state){u([...t.childNodes]);continue}}let h="template"===l?kt(t):null;if(null!==h){if("for"===h.b){let r=mt(e,h.Qe,n),s=Tt(e,t,r,!0);i(a(t,re.commentForPrefix),r,s)}else"if"===h.b?s(Nt(e,t,n).map((t,r)=>({O:Tt(e,t.el,n,!1),o:t.o,x:t.x,S:a(t.el,St(r,t))}))):bt(h.b);continue}let f=t.getAttribute(ct()),p=null===f?null:vt(e,f,n,t,0),m="noscript"!==l&&"iframe"!==l&&!p?.some(yt)&&!c.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.Wt&&d.data.includes("{{")&&!Et.has(d))for(let{a:e,cr:t}of _t(d))l(e,t);else if(8===d.nodeType){let e=Ct.exec(d.data),t=e&&d.parentNode.localName;if(null!==t&&"textarea"!==t&&"title"!==t){let t=document.createTextNode("");d.replaceWith(t),l(t,e[1])}}}};u(t)}var Ct=/^\s*@@\s*(?:wcs-text)?\s*:\s*([\s\S]+?)\s*$/,xt=e=>{let t=document.createRange();return t.selectNodeContents(e),e.content??t.cloneContents()};function Tt(e,t,n,r){let i=document.importNode(xt(t),!0),s=[],o=[],l=e=>s.push(e)-1;At(e,[...i.childNodes],n,!1,(e,t,n)=>{o.push({...ht(),a:l(e),i:6,o:t,O:n})},e=>{let t=e.map(e=>({a:l(e.S),O:e.O,o:e.o,x:e.x}));o.push({...ht(),a:t[0].a,i:7,K:t})},(e,t)=>{let n=l(e);for(let e of t)gt(e)&&_(203,[e.name]),e.a=n;o.push(...t),e.removeAttribute(ct())},(t,r)=>{o.push($t(e,r,n,l(t)))}),Lt(i,new Set(s),!0);let a=s.map(e=>function(e,t){let n=[];for(let r=t;r!==e;r=r.parentNode){let e=0;for(let t=r.previousSibling;null!==t;t=t.previousSibling)e++;n.unshift(e)}return n}(i,e)),u=1===i.childNodes.length&&8!==i.firstChild.nodeType,c=o.some(e=>6===e.i||7===e.i),h=[],d=new Set,f=[],p=[],m=r?n.n+1:-1;for(let e of o){if(5===e.i&&e.et&&!e.Ne&&!Pt(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&&Ot(e)&&(e.F=h.push(e)-1),7===e.i)for(let t of e.K)d.add(t.a);else d.add(e.a)}let g=[...d].sort((e,t)=>e-t);return{ln:i,root:u?i.firstChild:null,On:a,build:g,Ae:f,sr:p,In:u,lr:c,ko:[],Ye:h}}function Pt(e,t){for(;e.parentNode!==t;e=e.parentNode){if(e.parentNode.localName.includes("-"))return!0;for(let t=e.previousSibling;t;t=t.previousSibling)if(8===t.nodeType)return!0}return!1}function Ot(e){if(null!==e.U)return!1;switch(e.i){case 0:case 2:case 3:case 4:case 8:return!0;case 1:return!e.Ne&&null===e.At;default:return!1}}var Mt=new Set(["table","thead","tbody","tfoot","tr","colgroup","select","optgroup","datalist"]);function Lt(e,t,n){for(let r=e.firstChild;null!==r;){let e=r.nextSibling;3===r.nodeType?n&&!t.has(r)&&""===r.data.trim()&&r.remove():1===r.nodeType&&Lt(r,t,Mt.has(r.localName)),r=e}}var It=new WeakMap;function jt(e,t){let n=9===t.nodeType?t.body:t;e.root=t,It.set(t,e),Ht(e,[...n.childNodes]),e.Ke()}function Rt(e,t,n){try{let r="template"===t.localName?kt(t):null;null!==r&&!n&&_(204,[r.b]),Ht(e,[t])}catch(e){console.error(e)}e.Ke()}function Ht(e,t){At(e,t,null,!0,(t,n,r)=>{new lt(e,r,Ye(e,n,null,t),t).$t()},t=>{st(e,t,null,null)},(t,n)=>{c.jn?.(e,t,n);for(let r of n)it(e,r,t,null,null)},(t,n)=>{c.jn?.(e,t,n),it(e,$t(e,n,null,0),t,null,null)})}var Wt=Symbol.for("wcstack.binder"),Dt=Symbol.for("wcstack.binder.pending"),Ut=Symbol.for("wcstack.binder.taken"),zt=new Map;function Ft(e,t){if(1!==e.nodeType||!e.isConnected)return;let n=It.get(e.getRootNode());void 0===n||!1===n.element?.isConnected?zt.set(e,t):Rt(n,e,t?.range)}function qt(){let e=[...zt];zt.clear();for(let[t,n]of e)Ft(t,n);!function(){let e=function(){let e=globalThis[Wt];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}();if(null===e)return;let t=function(){let e=globalThis,t=e[Dt];return void 0===t&&(t=[],e[Dt]=t),t}();if(0===t.length)return;let n=t.splice(0,t.length),r=function(){let e=globalThis,t=e[Ut];return void 0===t&&(t=new WeakSet,e[Ut]=t),t}();for(let t of n)r.add(t),e.bind(t)}()}var Bt=class{constructor(){this.name="dirty",this.Z=(e,r)=>{if(0===e.n){let r=e.Y;return r!==t&&r!==n&&(e.Y=n,!0)}let i=null===r?null:r.yt;if(null===i)return!1;let s=i[e.F];return s!==t&&s!==n&&(i[e.F]=n,!0)}}Jo(e,t,n){null!==t.getter&&this.Z(t,n),e.Et(t,n),e.Nn(t,n,this.Z)}Ho(e,t){let n=t.l.o.It;if(null!==n)for(let r of n)r.n===t.l.n?e.it(r,t,this.Z):e.en(t,r,t=>e.it(r,t,this.Z))}be(e,t,n){this.Z(t,n),c.ke?.(e,t,n),e.Et(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.yt??=new Array(e.Le).fill(t),a=null===l?i.Y:l[i.F];if(a!==t&&a!==n&&a!==r&&(null===l||i.F in l))return a;a=r;try{return a=e.qo(i,null===l?null:s)}finally{null===l?i.Y=a:l[i.F]=a}}Xt(e){e.yt=null}vt(e){for(let t of e.I.all())null!==t.getter&&(0===t.n?t.Y===n&&(t.Y=r):e.nn(t.h[t.n],e=>{let i=e.yt;null!==i&&i[t.F]===n&&(i[t.F]=r)}))}},Gt=0,Kt=new WeakMap;function Vt(e,t=e.getRootNode()){Kt.set(t,[...Kt.get(t)??[],e].filter((e,t,n)=>e.isConnected&&n.lastIndexOf(e)===t))}function Jt(e){let t=Kt.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?Kt.get(e)!==t?Jt(e):Promise.reject(r.errors[0]):void 0)}var Qt=typeof HTMLElement>"u"?class{}:HTMLElement,Xt=class extends Qt{constructor(){super(),this.engine=null,this.Dn=!1,this.ze=!1,this.q=null,this.Xe=null,this.loaded=!1,this.un=null,this.connectedCallbackPromise=new Promise((e,t)=>{this.cn=e,this.$o=t}),this.connectedCallbackPromise.catch(()=>{}),this.initializePromise=new Promise(e=>{this.an=e})}static{this.getBindingsReady=Jt}static{this.hasConnectedCallbackPromise=!0}connectedCallback(){if(this.Dn){if(null!==this.Xe)return void this.Xe.Ge();Vt(this);let e=this.engine;if(null!==e){let t=e.root;t===this.getRootNode()&&!It.has(t)&&It.set(t,e),qt(),c.element?.(e,"back"),this.No("$connectedCallback",50,()=>{this.isConnected&&c.element?.(e,"connected")})}return}this.Dn=!0;let e=this.getRootNode(),t=c.ct?.(this,e);if(t)return this.Xe=t,!t.xo&&this.parentNode instanceof ShadowRoot&&Vt(this),void(void 0===t.Mt?this.Ro():t.Mt()).then(e=>(this.loaded=!0,t.start(e,()=>this.Po()))).then(()=>{this.an(),this.cn()},e=>this.Nt(e,t.xo));this.start(e),Vt(this)}disconnectedCallback(){if(null!==this.Xe)return void this.Xe.Ln();let e=this.engine;if(null===e)return;let t=e.root;It.get(t)===e&&It.delete(t),Vt(this,t),this.No("$disconnectedCallback",51),c.element?.(e,"disconnected")}setInitialState(e){if(this.ze&&_(14),this.loaded)this.Xe.reset(e);else if(null===this.engine)if(null!==this.un){let t=this.un;this.un=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.Be++;try{t(n.proxy)}finally{"readonly"===e&&n.Be--}}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(globalThis[Symbol.for("wcstack.ssr.resolveModule")]?.(t)??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//${++Gt}`);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.un=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.Dn=!1,void(this.isConnected&&this.connectedCallback());this.hasAttribute("enable-ssr")&&b("ssr","enable-ssr");let i=It.get(e)?.element;i?.isConnected&&(i.V||i.Xe)&&_(47);let s=new ne(n,new Bt);s.element=this,this.engine=s,c.element?.(s,"mounting"),jt(s,e),qt(),s.$n(),this.Po(),await s.Se("$connectedCallback"),this.isConnected&&c.element?.(s,"connected"),this.cn()}catch(e){this.ze=!this.V,this.Nt(e)}}Po(){this.V=!0,this.an()}Nt(e,t){this.Ke(this.V?50:49,e),this.an(),t?this.cn():this.$o(e)}Ke(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.Se(e))().then(n,e=>this.Ke(t,e))}},Yt=[];function Zt(){return(Yt=Yt.filter(e=>e.deref())).map(e=>e.deref())}var en,tn=e=>t=>{let n=e(t);return e=>null==e?e:n(e)},nn="en";function rn(){if(re.locale!==en){en=re.locale;try{nn=Intl.getCanonicalLocales(en)[0]}catch{console.warn(`[@wcstack/state] ${w(48,[en])}`),nn="en"}}return nn}var sn=["full","long","medium","short"];function on(e,t){let[n,r]=e??[];return void 0===r&&void 0!==n&&sn.includes(n)&&([n,r]=[void 0,n]),void 0!==r&&!sn.includes(r)&&function(e,t){_(52,[e,t])}(t,r),[n,r]}var{eq:ln,ne:an,not:un,lt:cn,le:hn,gt:dn,ge:fn,falsy:pn,truthy:mn,boolean:gn}=ke,yn={toFixed:{factory:e=>{let t=ve(e?.[0]??"0","toFixed");return e=>("number"!=typeof e&&ge("toFixed",e),e.toFixed(t))},arity:[0,1]},locale:{factory:e=>{let t=e?.[0];return e=>("number"!=typeof e&&ge("locale",e),e.toLocaleString(t??rn()))},arity:[0,1]},upper:{factory:tn(()=>e=>String(e).toUpperCase()),arity:[0,0]},lower:{factory:tn(()=>e=>String(e).toLowerCase()),arity:[0,0]},capitalize:{factory:tn(()=>e=>{let t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)}),arity:[0,0]},trim:{factory:tn(()=>e=>String(e).trim()),arity:[0,0]},slice:{factory:tn(e=>{let t=[we(e,0,"slice")],n=e?.[1];return typeof n<"u"&&t.push(ve(n,"slice")),e=>String(e).slice(...t)}),arity:[1,2]},padStart:{factory:tn(e=>{let t=we(e,0,"padStart"),n=e?.[1]??"0";return e=>String(e).padStart(t,n)}),arity:[1,2]},padEnd:{factory:tn(e=>{let t=we(e,0,"padEnd"),n=e?.[1]??" ";return e=>String(e).padEnd(t,n)}),arity:[1,2]},repeat:{factory:tn(e=>{let t=we(e,0,"repeat");return e=>String(e).repeat(t)}),arity:[1,1]},reverse:{factory:tn(()=>e=>String(e).split("").reverse().join("")),arity:[0,0]},truncate:{factory:tn(e=>{let t=we(e,0,"truncate"),n=e?.[1]??"…";return e=>{let r=String(e);return r.length<=t?r:r.slice(0,t)+n}}),arity:[1,2]},join:{factory:e=>{let t=e?.[0]??", ";return e=>(Array.isArray(e)||_(30,["join"]),e.join(t))},arity:[0,1]},round:{factory:e=>{let t=Math.pow(10,ve(e?.[0]??"0","round"));return e=>("number"!=typeof e&&ge("round",e),Math.round(e*t)/t)},arity:[0,1]},floor:{factory:e=>{let t=Math.pow(10,ve(e?.[0]??"0","floor"));return e=>("number"!=typeof e&&ge("floor",e),Math.floor(e*t)/t)},arity:[0,1]},ceil:{factory:e=>{let t=Math.pow(10,ve(e?.[0]??"0","ceil"));return e=>("number"!=typeof e&&ge("ceil",e),Math.ceil(e*t)/t)},arity:[0,1]},percent:{factory:e=>{let t=ve(e?.[0]??"0","percent");return e=>("number"!=typeof e&&ge("percent",e),`${(100*e).toFixed(t)}%`)},arity:[0,1]},unit:{factory:tn(e=>{let t=e?.[0]??pe("unit");return e=>String(e)+t}),arity:[1,1]},date:{factory:e=>{let[t,n]=on(e,"date"),r=n&&{dateStyle:n};return e=>(e instanceof Date||ye("date",e),e.toLocaleDateString(t??rn(),r))},arity:[0,2]},time:{factory:e=>{let[t,n]=on(e,"time"),r=n&&{timeStyle:n};return e=>(e instanceof Date||ye("time",e),e.toLocaleTimeString(t??rn(),r))},arity:[0,2]},datetime:{factory:e=>{let[t,n]=on(e,"datetime"),r=n&&{dateStyle:n,timeStyle:n};return e=>(e instanceof Date||ye("datetime",e),e.toLocaleString(t??rn(),r))},arity:[0,2]},ymd:{factory:e=>{let t=e?.[0]??"-";return e=>{e instanceof Date||ye("ymd",e);let n=e.getFullYear().toString(),r=(e.getMonth()+1).toString().padStart(2,"0"),i=e.getDate().toString().padStart(2,"0");return`${n}${t}${r}${t}${i}`}},arity:[0,1]},hms:{factory:e=>{let t=e?.[0]??":";return e=>{e instanceof Date||ye("hms",e);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:ln,ne:an,not:un,lt:cn,le:hn,gt:dn,ge:fn,add:$e("add",(e,t)=>e+t),sub:$e("sub",(e,t)=>e-t),mul:$e("mul",(e,t)=>e*t),div:$e("div",(e,t)=>e/t),mod:$e("mod",(e,t)=>e%t),abs:{factory:()=>e=>("number"!=typeof e&&ge("abs",e),Math.abs(e)),arity:[0,0]},clamp:{factory:e=>{let t=we(e,0,"clamp"),n=we(e,1,"clamp");return e=>("number"!=typeof e&&ge("clamp",e),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:pn,truthy:mn,defaults:{factory:(e,t)=>{let n=_e(e?.[0]??pe("defaults"),t);return e=>e||n},arity:[1,1]},coalesce:{factory:(e,t)=>{let n=_e(e?.[0]??pe("coalesce"),t);return e=>e??n},arity:[1,1]},boolean:gn,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]},currency:{factory:e=>{let t=e?.[0]??pe("currency"),n=e?.[1],r={style:"currency",currency:t};try{new Intl.NumberFormat("en",r);let e=Intl.supportedValuesOf?.("currency");if(e&&!e.includes(t.toUpperCase()))throw 0}catch{!function(e){_(53,[e])}(t)}return e=>("number"!=typeof e&&ge("currency",e),e.toLocaleString(n??rn(),r))},arity:[1,2]}},bn=!1,vn={name:"formats",install:function(){bn||(bn=!0,de(yn))}};function wn(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 _n(e,t){if(0===e.length)return"";let n=e.toLowerCase(),r=null,i=3;for(let e of t){let t=wn(n,e.toLowerCase(),2);t<i&&(r=e,i=t)}return null!==r?` Did you mean "${r}"?`:""}var $n=" Validate statically: npx @wcstack/lint <file>.",kn=["","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"],Sn=e=>{let t=kn[e/100|0];return t?`[wcs/${t}] `:""},Nn=["enableMustache","sameValueGuard","enableDirectionalInitialSync"],En=e=>null==e?String(e):e instanceof Date?"a Date":Array.isArray(e)?"an array":"string"==typeof e?`a string (${JSON.stringify(e.length>32?e.slice(0,32)+"…":e)})`:"object"==typeof e?"an object":`a ${typeof e} (${String(e)})`,An=["","","class.","attr.","style."],Cn=(e,t)=>`<${e}${t.map((e,t)=>t%2?`="${e}"`:` ${e}`).join("")}>`,xn="https://github.com/wcstack/wcstack/blob/main/docs/csp.md",Tn={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,n,r)=>`binding "${n?(An[r]??"")+n: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 ${xn}`,43:e=>`Failed to evaluate the inline <script> of <wcs-state>: ${e}. If this page sets a Content-Security-Policy, see ${xn}`,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,t)=>`filter ${e} requires a number value, not ${En(t)}${"string"==typeof t?` — put |number before |${e}, or convert it where it is read`:""}`,29:(e,t)=>`filter ${e} requires a date value (a Date), not ${En(t)}${"string"==typeof t||"number"==typeof t?" — make the Date where it is read: a getter returning new Date(…)":""}`,52:(e,t)=>`filter ${e} takes a style of full, long, medium or short, not "${t}"`,53:e=>`filter currency takes an ISO 4217 currency code (JPY, USD, EUR), not "${e}"`,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&&Nn.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)=>`${Cn(e,t)} failed to initialize.`,50:(e,...t)=>`${Cn(e,t)} $connectedCallback failed.`,51:(e,...t)=>`${Cn(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>").`,122:(e,t)=>"class"===t?`"${e}": "class:" needs a class name — "class.NAME:" toggles one class (a bare "class:" would set an element property named "class", which does nothing). To set the whole class attribute, bind "className:".`:`"${e}": "attr:" needs an attribute name — "attr.NAME:" sets one attribute (a bare "attr:" would set an element property named "attr", which does nothing).`,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 Pn(e,t){let n=Tn[e];return void 0===n?`${Sn(e)}#${e} ${t.join(" ")}`:Sn(e)+n(...t)}var On=new Set(["binding-syntax","template-syntax","filter-unknown","filter-arity","index-arity","wildcard-rank","token-undeclared","binding-path-missing","index-param-range"]),Mn=[[/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.']],Ln={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function In(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(Ln,e)?Ln[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?_n(t,n):"");for(let[t,n]of Mn){let i=t.exec(e);null!==i&&(r+=n.replace(/\$(\d)/g,(e,t)=>i[Number(t)]))}let i=/"([^"#]+)#([^"]+)": a binding takes one modifier list/.exec(e);null!==i&&(r+=` — write "${i[1]}#${i[2].split("#").join(",")}".`),e.includes("[wcs/filter-unknown]")&&(e.includes("formats add-on")?r+=' On a split auto page: features="formats" on the root, or "$features": ["formats"].':ue.some(fe)||(r+=' No formatting filters are installed — add the formats add-on: installFeatures([formats]) from "@wcstack/state/features/formats" (a split auto page: features="formats", or "$features").'));let s=/\[wcs\/([\w-]+)\]/.exec(e);return null!==s&&On.has(s[1])&&!/ path segments — the limit is |inserted content was not rendered|formats add-on/.test(e)&&(r+=$n),r}var jn=new WeakMap,Rn=new WeakMap,Hn=new WeakSet,Wn=new WeakSet;function Dn(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 Un(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 zn(e,t){let n=[];for(let e=t;null!==e;e=e.d)n.unshift(e);let r=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!==Dn(e.target,t.t)?.get?t:e.I.jt(o(t.t).o)}(e,t);return n.some(e=>null!=r(e)?.getter)?null:Fn(e,n,0,e.target,r)}function Fn(e,t,n,r,i){for(;n<t.length;n++){let s=t[n];if(null===r||"object"!=typeof r)return null;if("*"===s.s){if(!Array.isArray(r)||0===r.length)return null;let s=null;for(let o of r){let r=Fn(e,t,n+1,o,i);if(null===r)return null;if(null===s)s=r;else if(r.seg===s.seg)for(let e of r.names)s.names.includes(e)||s.names.push(e)}return s}if(Array.isArray(r)&&/^\d+$/.test(s.s)){if(Number(s.s)>=r.length)return null;r=r[Number(s.s)];continue}let o=Dn(r,s.s);if(void 0===o&&null===s.d&&e.vt.has(s.s))return null;if(void 0===o){let t=Un(r),n=i(s.d);for(let r of e.I.all())r.d===n&&null!==r.getter&&t.push(r.s);return{seg:s.s,names:t}}if(void 0!==o.get||void 0!==o.set)return null;r=o.value}return null}function qn(e){Hn.has(e)||(Hn.add(e),setTimeout(()=>function(e){Hn.delete(e);let t=jn.get(e);if(void 0===t)return;let n=Rn.get(e);void 0===n&&Rn.set(e,n=new Set);for(let[r,i]of t){if(n.has(r))continue;n.add(r);let t=zn(e,r);if(null===t)continue;let s=[...e.root?.querySelectorAll(`${re.tagNames.state}[mount]`)??[]].find(e=>!Wn.has(e)&&(r.t+".").startsWith(e.getAttribute("mount")+"."));if(void 0!==s){n.delete(r),s.initializePromise.then(()=>{Wn.add(s),qn(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.jt(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.${_n(t.seg,t.names)}${h} Updates to this path will be silently dropped.${$n}`)}}(e),0))}function Bn(e,t,n=!1){if("$"===t.t[0]||t.t.includes("#")||!n&&null===t.d)return;let r=jn.get(e);void 0===r&&jn.set(e,r=new Map),r.has(t)||r.set(t,n),qn(e)}var Gn=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Kn=!1;function Vn(e,t,n){let r="html"===n.name?"innerHTML":n.name;if(Kn||!(t instanceof TypeError)||!xe(r)||!("trustedTypes"in globalThis))return;Kn=!0;let i="function"==typeof Ce()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/state deliberately does not pass state values through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/state] Writing to "${r}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${i}\nInstall a sanitizing policy before the first binding is applied:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr bind the value as text instead of HTML. See docs/csp.md section 7.`,{element:n.a,property:r})}var Jn=new WeakMap;function Qn(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=Jn.get(e);void 0===s&&Jn.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 Xn=[["$streams","$stream"],["$updatedCallback","$renderedCallback"]],Yn={$trackDependency:"$dependOn",$untrackDependency:"$untracked"},Zn={name:"diagnostics",install(){c.Lo=In,c.Bo=Pn,c.So=Bn,c.detail=Qn,c.ze=h(c.ze,Vn);let e=c.de;c.de=(t,n)=>{(function(e){void 0!==e.$scan&&_(1);for(let[t,n]of Xn)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=Un(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(`^(?:${Gn(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(`^${Gn(r)}(?:${Gn(l)})*${Gn(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){Rn.delete(e),jn.has(e)&&qn(e)}(t)},c.ot=d(p,c.ot,(e,t)=>Object.hasOwn(Yn,t)?_(1701,[t,Yn[t]]):void 0)}},er={},tr=/\.\d/,nr=new Set(Object.getOwnPropertyNames(Object.prototype)),rr=0,ir=!1,sr=null,or=()=>{ir=!1,rr++};function lr(){if(null===sr)if("function"==typeof MessageChannel){let e=new MessageChannel;e.port1.onmessage=or,e.port1.unref?.(),sr=()=>e.port2.postMessage(0)}else sr=()=>setTimeout(or,0);return ir||(ir=!0,sr()),rr}function ar(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 ur=class{constructor(e,t){this.active=!1,this.Te=new Map,this.early=[],this.n=0,this.Ao=-1,this.Bn=new Set,this.Ue=null,this.engine=e,this.je=t}ur(){let e=this.engine;this.Te.clear();let t=this.early;this.early=[];for(let t of this.je)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(er,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;let n=new Set;for(let[r,i,s,o]of t)if((null===i||i.w)&&Object.is(e.v(r,i),o)){n.add(r);for(let e of this.je)e.p===r&&this.ut(e,i,s,!0)}for(let e of this.je)e.getter&&0===e.p.n&&!this.Te.has(e)&&ar(cr(e.p),n)&&this.ut(e,null,void 0,!0);this.Te.size>0&&e.we()}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.Te.clear(),this.early=[]}Mn(e,t,n,r){let i=this.engine.He(n,e.h[t]);for(let n of i.f)t===e.n?r(n):this.Mn(e,t+1,n,r)}ut(e,t,n,r){let i=this.Te.get(e);void 0===i&&this.Te.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)}ve(e,t,n,r,i,s){if(this.active){(this.Ue??=new Set).add(e);for(let s of this.je){let o=s.p;o.n!==e.n||!o.ee(e)||this.ut(s,t,s.getter?s.s.get(t??er):o===e&&i&&this.engine._t&&(null===r||"object"!=typeof r&&"function"!=typeof r)?n:void 0,!0)}}else s&&this.early.push([e,t,n,r])}ke(e,t){if(this.active)for(let n of this.je)(n.getter||=null!==n.p.getter||n.p.se)&&n.p.n===e.n&&n.p.ee(e)&&this.ut(n,t,n.s.get(t??er),!1)}Qt(e,t){if(!this.active)return;let n=null;for(let r of this.je){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.ut(r,t,void 0,!0):this.Mn(i,e.n+1,t,e=>this.ut(r,e,void 0,!0)))}}}Ce(){let e=this.Ue;if(this.Ue=null,!this.active||0===this.Te.size)return;let t=this.Te;this.Te=new Map;let n=this.engine,r=[];for(let i of this.je){let s=t.get(i);if(void 0===s)continue;let o,l=[...s].filter(([e])=>null===e||e.w);l.length>1&&l.sort((e,t)=>hr(e[0],t[0]));for(let[t,[s,a,u]]of l){let l,h="evaluate",d=n.u;this.n=a+1,n.Fe++;try{if(l=n.v(i.p,t),i.getter&&(i.s.set(t??er,l),Object.is(l,s)&&(tr.test(i.t)||null!==t&&!u&&!(o??=null!==e&&ar(cr(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.Fe--}}}r.length>0&&this.Oo(r)}Oo(e){let t=lr();t!==this.Ao&&(this.Ao=t,this.Bn.clear());let n=e.filter(e=>!this.Bn.has(e));if(0!==n.length){for(let e of n)this.Bn.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 cr(e){for(;null===e.getter&&null!==e.d;)e=e.d;return e}function hr(e,t){let n=[],r=[];for(let t=e;null!==t;t=t.l.ae)n.unshift(t.y);for(let e=t;null!==e;e=e.l.ae)r.unshift(e.y);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 dr="$streamStatus",fr="$streamError",pr=new Set(Object.getOwnPropertyNames(Object.prototype)),mr=!1;function gr(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 yr=class{constructor(e,t,n){this.engine=e,this.entries=t,this.M=n}set(e,t,n){mr=!0;try{this.engine.A(this.engine.o(`${e}.${t}`),null,n)}finally{mr=!1}}dr(){for(let e of this.entries)this.start(e,!0)}fr(){for(let e of this.entries)e.dt=!1,e.J?.abort(),e.J=null}pr(){for(let e of this.entries)e.dt=!1,null!==e.J&&(e.J.abort(),e.J=null),this.set(dr,e.name,"idle")}ke(e){let t=this.M.n;for(let n of this.entries)n.g===e&&(n.n=n.dt?Math.max(n.n,t):t,n.dt=!0)}Ce(){let e=this.engine,t=this.M,n=[];for(let i of this.entries){if(!i.dt)continue;let s=i.n;if(i.dt=!1,s>32)n.push(i.name),i.g.Y=r;else{t.n=s+1,e.Fe++;try{this.start(i,!1)}finally{e.Fe--,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();br(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===`${dr}.${e}`||n.t===`${fr}.${e}`)&&v(`$stream "${e}": args must not read the stream itself ("${n.t}").`)}(e.name,s,n)}catch(n){br(s);for(let e of o)e._n(s);if(s.Y=r,t)throw n;return this.set(fr,e.name,n),void this.set(dr,e.name,"error")}}let s=new AbortController;e.J=s,i.A(i.o(e.name),null,e.q),this.set(fr,e.name,null),this.set(dr,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.M.n,a=lr(),u=e=>{lr()===a&&(this.M.n=l);try{e()}finally{this.M.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.A(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(dr,e.name,"done"))}catch(n){if(!s())return;e.J=null,t.abort(),u(()=>{this.set(fr,e.name,n),this.set(dr,e.name,"error")})}}};function br(e){for(let t of e.Q){let n=t.W.indexOf(e);n>=0&&t.W.splice(n,1),t.mt.delete(e)}e.Q.length=0,e.Y=t}var vr=new WeakMap;function wr(e){let t=vr.get(e);return t?.target===e.target?t:void 0}function _r(e,t){let n=new ur(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("@")||nr.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 yr(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)||pr.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.`),gr(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,dt:!1,n:0,g:void 0===c?null:e.o(`$streamArgs.${o}`),args:void 0===c?null:function(){return c(this)}})}return t[dr]=i,t[fr]=s,r}(e,t),n),i=vr.get(e);void 0!==i&&(i.M.Fo(),i.Ot.fr()),vr.set(e,{M:n,Ot:r,Ge:i?.Ge??!1,target:t})}function $r(e,t){let n=vr.get(e);if(void 0!==n&&"mounting"!==t&&!document.documentElement?.hasAttribute("data-wcs-server")&&("reset"!==t&&(n.Ge="connected"===t),n.target===e.target)){if("disconnected"===t)return n.M.Fo(),void n.Ot.pr();n.Ge&&(n.M.ur(),n.Ot.dr())}}var kr=["$streamStatus","$streamError"],Sr={name:"temporal",install(){c.de=h(c.de,_r),c.element=h(c.element,$r),c.ve=h(c.ve,(e,t,n,r,i,s,o)=>wr(e)?.M.ve(t,n,r,i,s,o)),c.ke=h(c.ke,(e,t,n)=>{let r=wr(e);void 0!==r&&(r.M.ke(t,n),r.Ot.ke(t))}),c.Qt=h(c.Qt,(e,t,n)=>wr(e)?.M.Qt(t,n)),c.Ce=h(c.Ce,e=>{let t=wr(e);void 0!==t&&(t.M.Ce(),t.Ot.Ce())}),c.ot=d(p,c.ot,(e,t)=>{let n=t.split(".",1)[0];if(kr.includes(n))return n===t?e.target[t]:e.read(e.o(t),null)}),c.Oe=d(f,c.Oe,(e,t)=>(!mr&&36===t.t.charCodeAt(0)&&kr.includes(t.t.split(".",1)[0])&&v(`"${t.t}" is read-only (the stream runtime owns it).`),!1))}},Nr=new WeakMap,Er=!1,Ar=/^(?!prototype$)[^\d.*$][^.*]*$/;function Cr(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.`)}}Nr.set(t,r)}function xr(e){if(null===e||"object"!=typeof e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function Tr(e,t,n){let r=new Map;for(let i of t){xr(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 Pr(e,t,n,r){if(Er||!Array.isArray(r))return!1;let i=Nr.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=Tr(t.t,s,i);Tr(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){Er=!0;try{e.A(t,n,l)}finally{Er=!1}}if(c.length>0){let r=e.He(0===t.n?null:n,t);for(let[n,i,s]of c){if("__proto__"===i)continue;let o=r.f[n],l=Ar.test(i)?e.o(`${t.t}.*.${i}`):null;null===l?.getter?e.A(l,o,s):(o.$[i]=s,e.A(e.o(`${t.t}.*`),o,o.$,!0))}}return!0}var Or={name:"list-keys",install(){c.de=h(c.de,Cr),c.Oe=d(f,c.Oe,Pr)}},Mr=new WeakMap,Lr=new WeakMap,Ir="will not graft: the root state failed to initialize.",jr=new WeakSet,Rr=new WeakMap,Hr=["$stream","$streams","$scan","$recursion","$watch","$listKeys","$renderedCallback","$updatedCallback","$behavior","$features"],Wr=["$commandTokens","$eventTokens","$on","$errorCallback"],Dr=e=>`[@wcstack/state] <${re.tagNames.state} mount="${e}">`,Ur=new Set(["$getAll","$setAll","$resolve","$postUpdate","$dependOn","$eq","$eqIndex"]),zr=e=>e?.element?.isConnected?e:void 0;function Fr(e){let t=Lr.get(e);return void 0!==t&&!Array.isArray(t)&&t.isConnected}function qr(e,t){let n=Lr.get(t);if(Lr.delete(t),Array.isArray(n))for(let t of n)Vr(t,e)}function Br(e){let t=Mr.get(e.root);t?.get(e.t)===e&&t.delete(e.t)}function Gr(e,t){console.error(`${Dr(e.t)} ${t}`),Br(e),e.Je?.(),e.Je=null}function Kr(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 Vr(e,t){if(jr.has(t))return Gr(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 Gr(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)):Ur.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.A(n,null,{})}t.A(t.o(e.t),null,l)}t.to(Object.defineProperties({},a));for(let e in a)t.Ue(t.o(e),null);e.engine=t;let c=Rr.get(t);void 0===c&&Rr.set(t,c=[]),c.push(e),e.el.isConnected&&Kr(e,"$connectedCallback"),e.Je?.(),e.Je=null}function Jr(e,t){let n=Lr.get(e);if(Array.isArray(n))for(let e of n)Gr(e,Ir);Lr.set(e,t)}var Qr=new WeakMap;function Xr(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(re.bindAttributeName))i='injections (data-wcs="state.<key>: …") are not supported — read the root path in a root getter.';else{let e=Mr.get(t);void 0===e&&Mr.set(t,e=new Map);let s=e.get(n);if(void 0!==s&&s!==r&&(null===s.engine?s.el.isConnected:zr(s.engine)))i=`will not graft: another volume already holds "${n}".`;else{if(null===s?.engine){let e=Lr.get(t);Array.isArray(e)&&Lr.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 Gr(r,i);if(Mr.get(t).get(n)===r){for(let t of Hr)if(void 0!==e[t])return Gr(r,`${t} is not run in a volume — declare it on the root state.`);for(let t of Wr)void 0!==e[t]&&console.warn(`${Dr(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=zr(It.get(t)),i=Lr.get(t);void 0!==n?Vr(r,n):Fr(t)?Gr(r,Ir):Lr.set(t,[...Array.isArray(i)?i:[],r])})}},Ge(){null!==r.engine&&Kr(r,"$connectedCallback")},Ln(){null!==r.engine&&Kr(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 Yr=new WeakMap,Zr=new WeakMap;function ei(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 ti(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=ei(r,"$bindables"),o=ei(r,"$commands");for(let e of s){let t=i.get(e);void 0===t&&v(`$bindables entry "${e}" does not exist on the state.`),"function"==typeof t.value&&v(`$bindables entry "${e}" is a method: list it in $commands.`)}for(let e of o){let t=i.get(e);void 0===t&&v(`$commands entry "${e}" does not exist on the state.`),"function"!=typeof t.value&&v(`$commands entry "${e}" is not a method: list it in $bindables.`)}let l={tag:e,bindables:s},a=new WeakMap,u=new WeakMap,c=r=>{if(a.has(r))return a.get(r);if(r.hasAttribute("data-wc-definition"))return null;let i=r.attachShadow({mode:n});i.appendChild(t.cloneNode(!0));let o=i.querySelector(re.tagNames.state);return a.set(r,o),Yr.set(r,l),null===o&&s.length>0&&console.warn(`[@wcstack/state] DCC: <${e}> declares $bindables but its content has no <${re.tagNames.state}>: no change events.`),o},h=e=>c(e)?.engine??null,d=e=>Promise.resolve(c(e)?.initializePromise).then(()=>{let t=u.get(e);u.delete(e);let n=h(e);if(void 0!==t&&null!==n)for(let[e,r]of t)n.proxy[e]=r});class f extends HTMLElement{static{this.wcBindable=0===s.length&&0===o.length?null:{protocol:"wc-bindable",version:1,properties:s.map(t=>({name:t,event:`${e}:${t}-changed`,getter:e=>e.target[t]})),inputs:s.map(e=>({name:e})),...0===o.length?{}:{commands:o.map(e=>({name:e,async:!0}))}}}connectedCallback(){null!==c(this)&&d(this)}get stateElement(){return c(this)}}for(let[e,t]of i)"function"==typeof t.value?Object.defineProperty(f.prototype,e,{configurable:!0,value(...t){return d(this).then(()=>{let n=h(this);return null===n?void 0:n.proxy[e].apply(n.proxy,t)})}}):Object.defineProperty(f.prototype,e,{configurable:!0,get(){return h(this)?.proxy[e]},set(t){let n=h(this);if(null!==n)n.proxy[e]=t;else{let n=u.get(this);void 0===n&&u.set(this,n=[]),n.push([e,t])}}});customElements.define(e,f)}(n.localName,r,i,t)},Ge(){},Ln(){},reset(){v("re-setting a DCC definition is not supported: each instance loads its own state.")}}}var ni=new WeakMap,ri=new WeakSet,ii=new WeakMap,si=new WeakMap,oi="data-wcs-wired",li=new WeakMap,ai=new WeakMap,ui=new WeakMap,ci=0,hi=new Set,di={},fi=["$watch","$stream","$renderedCallback"],pi=e=>e.split(".",1)[0];function mi(e,t){let n=0;return e.split(".").map(e=>"*"===e?String(t[n++]):e).join(".")}function gi(e,t){let n=e.a,r=pi(e.name);if(!0!==document.documentElement?.hasAttribute("data-wcs-server"))n.removeAttribute(oi);else if(!bi(n,r)){let e=n.getAttribute(oi)?.split(" ")??[];e.includes(r)||n.setAttribute(oi,[...e,r].join(" "))}li.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=ni.get(n);void 0===i&&ni.set(n,i=[]),i.push(e),t&&ri.add(e);let s=ii.get(n);return void 0===s&&ii.set(n,s=new Map),s.has(r)||s.set(r,n[r]),si.get(n)?.(),!1}function yi(e){return e.localName.includes("-")&&null!==e.querySelector(`:scope > ${re.tagNames.state}[bind-component]`)}function bi(e,t){let n=e.getAttribute(re.bindAttributeName);return null!==n&&new RegExp(`(^|;)\\s*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[.#:]`).test(n)}function vi(e){let t=e.parentElement;for(;null!==t&&!yi(t);)t=t.parentElement;let n=It.get(t??e.getRootNode()),r=n?.element;(r?.isConnected?r.V:null===t)&&(null===t?Ft(e):Rt(n,e))}var wi=new Set;function _i(e,t){wi.has(e)||(wi.add(e),console.warn(`[@wcstack/state] ${t}`))}var $i=(e,t)=>t in e.state;function ki(e,t){let n=Si(e.state,t);return void 0!==n&&(void 0!==n.get||void 0!==n.set||"function"==typeof n.value)}function Si(e,t){for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e}}function Ni(e,t,n){if(null!==n.getter)return;let r,i=e.host,s=i.engine,o=pi(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.ft.get(r));)r=r.d;if(null===r||void 0===n)return;let i=e.R,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=Ei(e,l.r);return 0===t.n?n:(s.resolve(mi(o.t,[...s.H(n),...i.H(ee(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();Ai(e,l.e,()=>s.A(o,r,n)),e.dn=t}),t.n>0&&(t.F=i.Le++),e.ft.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?$i(i,o):ki(i,o))return;r=l.me}else{if(null===t||null!==n.d||"$"===o[0]||$i(i,o))return;l=t,r=s.o(`${t.me.t}.${o}`)}let a=l.r,u=l;n.getter=()=>s.v(r,Ei(e,a)),n.ie=t=>{Ai(e,u,()=>s.A(r,a,t)),e.dn=n},e.ft.set(n,{e:l,p:r,r:a})}function Ei(e,t){return null!==t&&!t.w&&v(`The host row of <${e.host.el.localName}> was removed.`),t}function Ai(e,t,n){let r=hi.has(e.R);hi.add(e.R),e.from=t;try{n()}finally{r||hi.delete(e.R),e.from=null}}var Ci=(e,t)=>t||!hi.has(e.m.R)||null!==e.m.from&&e.m.from!==e.e;function xi(e,t){if(e.fn===t||null===e.host.engine)return;e.fn=t,ci+=t?1:-1;let n=e.host.engine,r=ui.get(n);void 0===r&&ui.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=pi(o);if(o!==a&&!$i(n,a))continue;let u=r.o(`${t.me.t}.${o}`);if(null===u.getter)Oi(r,u,t.me);else if(!Ti.has(u.getter))continue;e.re.set(u,e.R.o(o))}}(e,i);for(let r of e.re.keys())t&&null===r.getter&&Oi(n,r,i.me),n.T.be(n,r,i.r);e.re.size>0&&n.we(),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;_i(`${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 Ti=new WeakSet;function Pi(e,t,n,r){let i=ui.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 Oi(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=Pi(e,n,e.u,t);return null===o?void 0:o.R.read(o.re.get(t),null)},Ti.add(t.getter),t.ie=o=>{let l=null===s()?Pi(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===Si(l.host.state,a.t)?.set&&v(`Cannot write to "${a.t}" on mounted <${l.host.el.localName}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),l.R.A(a,null,o)},t.n>0&&(t.F=e.Le++)}function Mi(e,t,n,r,i,s){if(null!==t.getter)return e.T.be(e,t,n),void e.we();if("*"===t.s){if(null===n)return;if(n.$=n.l.P[n.y],e.T.Xt(n),null!==n.c)for(let t of n.c.values())e.G(t)}else e.En(t,n);c.ve?.(e,t,n,r,i,s),e.Ue(t,n)}function Li(e){let t=e.m.R;for(let[n,r]of e.m.ft)r.e===e.e&&(0===n.n?t.T.be(t,n,null):t.nn(n.h[n.n],e=>t.T.be(t,n,e)));t.we()}function Ii(e,t,n,r,i,s,o){let l=n.t.slice(t.t.length);if(""===l)return Li(e);let a,u=e.m,c=u.R;if(""===e.e.E){a=l.slice(1);let e=pi(a);if("$"===e[0]||$i(u.host,e)||u.host.entries.some(e=>""!==e.E&&(a===e.E||a.startsWith(`${e.E}.`))))return}else a=e.e.E+l;let h=[];for(let e=t.n+1;e<=n.n;e++)h.push(ee(r,e).y);c.resolve(mi(a,h),null);let d=c.rp,f=c.rr;d.n>0&&null===f||Mi(c,d,f,i,s,o)}function ji(e,t,n,r,i,s,o){if(0===ci)return;let l=hi.has(e);hi.add(e);try{let l=ai.get(e);!o&&void 0!==l&&l.fn&&!hi.has(l.host.engine)&&function(e,t,n,r,i,s){let o,l=t;for(;null!==l&&void 0===(o=e.ft.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.w)return;let u=[...a.H(o.r),...e.R.H(n)];a.resolve(mi(o.p.t+t.t.slice(l.t.length),u),null);let c=a.rp,h=a.rr;c.n>0&&null===h||Ai(e,o.e,()=>Mi(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.T.be(r,i,n.r),r.we())}(l,t);let a=ui.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:ee(n,e.n));if(void 0!==a)for(let l of[...a])Ci(l,o)&&Ii(l,e,t,n,r,i,s)}else if(e.ee(t))for(let[e,r]of[...l])if(0===t.n||ee(e,t.n)===n)for(let e of[...r])Ci(e,o)&&Li(e)}finally{l||hi.delete(e)}}async function Ri(e,t,n,r,i){if(r===di)return;let s=y(r);s&&await s;let o=li.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.C;if(null!==l&&l.el!==e&&l.el.isConnected&&v(`<${t.localName}> already has a connected <${re.tagNames.state} bind-component="${o.pe}">.`),null!==l&&xi(l,!1),null!==l&&function(e,t,n){let r=e.R,i=`[${re.bindAttributeName}]`,s=e=>1===e.nodeType&&(e.matches(i)||null!==e.querySelector(i)),o=new Set,l=e=>{for(;null!==e&&e.parentNode!==n;)e=e.parentNode;null!==e&&o.add(e)},a=(e,t)=>{for(let n=e.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.j)l(t.a);else for(let e of t.j.K)a(t.j,e.S);for(let e of r.oe.values())for(let t of[e.N,...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.Wt&&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.R.element=t,t.engine=e.R,e.L=e.L.filter(e=>e.parentNode===n),t.isConnected?await Hi(e,r):r()}(l,e,n,i);let a=new ne(r,new Bt);a.element=e,e.engine=a,function(e,t){let n=new Map;for(let e=t;null!==e&&e!==Object.prototype;e=Object.getPrototypeOf(e))for(let t of Object.getOwnPropertyNames(e)){let r=Object.getOwnPropertyDescriptor(e,t).value;"function"==typeof r&&"constructor"!==t&&n.set(r,null)}let r=(t,n,r)=>Reflect.apply(t,e.proxy,r);e.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:[],R:a,host:o,fe:[],ft:new Map,fn:!1,dn:null,from:null,re:null};for(let e of o.entries)u.fe.push({m:u,e:e});o.C=u,ai.set(a,u);let h=null===o.engine;h?c.element?.(a,"mounting"):(function(e){let t=e.R,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=pi(e.E);$i(n,t)&&(e.E!==t||ki(n,t))&&_i(`${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)&&_i(`${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=fi.filter(e=>void 0!==n.state[e]);o.length>0&&_i(`${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=>{Ni(e,s,n),l.call(t,n)};let a=[...t.I.all()];for(let t of a)Ni(e,s,t);for(let e of a)l.call(t,e);let u=t.Yt;t.Yt=()=>{(function(e){for(;void 0!==e;e=ai.get(e.host.engine))if(e.host.entries.some(e=>null!==e.r&&!e.r.w))return!1;return!0})(e)&&u.call(t)}}(u),xi(u,!0),jr.add(a),qr(a,n));let d=c.hr?.(n);jt(a,n),d?.(),u.L=[...n.childNodes],qt(),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.Se("$connectedCallback"),h&&e.isConnected&&c.element?.(a,"connected")):xi(u,!1)}async function Hi(e,t){xi(e,!0);for(let t of e.fe)Li(t);t?.(),!e.broken&&(await e.R.Se("$connectedCallback"),null===e.host.engine&&e.el.isConnected&&c.element?.(e.R,"connected"))}function Wi(e,t){let n=e.getAttribute("bind-component");if(null===n)return function(e,t){return e.connectedCallbackPromise.catch(()=>{let n=It.get(t)?.element;if(!(e.V||void 0!==n&&n!==e&&n.isConnected)){Jr(t,e);for(let e of Qr.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:li.get(s)?.C;return t?.el===e?t:null},l=t=>{throw i&&Jr(r,e),t},a=!1;return{Mt:()=>(null!==s&&s.localName.includes("-")?async function(e,t,n,r){let i=n.localName;(["state","src","json"].some(t=>e.hasAttribute(t))||null!==e.querySelector('script[type="module"]'))&&v(`<${re.tagNames.state} bind-component> takes its state from <${i}>.${t}: it cannot also load one (state / src / json / an inline script).`),await Ie(n).whenDefined(i);let s=li.get(n);if(void 0!==s)return s.pe!==t&&v(`<${i}> already has a <${re.tagNames.state} bind-component="${s.pe}">.`),s.state;let o=()=>(ni.get(n)??[]).filter(e=>pi(e.name)===t),l=bi(n,t);if(l&&0===o().length&&vi(n),0===o().length&&(l||((e,t)=>!0===e.getAttribute(oi)?.split(" ").includes(t))(n,t))){let e;await new Promise((r,s)=>{si.set(n,r),e=function(e,t){Fr(e)&&t();let n=Qr.get(e)??new Set;return Qr.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())}si.delete(n);let a=o(),u=ii.get(n),c=void 0!==u&&u.has(t)?u.get(t):n[t];if((null===c||"object"!=typeof c)&&v(`"bind-component": <${i}>.${t} must be an object (the component's state), got ${null===c?"null":typeof c}.`),0===a.length&&r){let e=new Error(`[@wcstack/state] A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${i}>, or mount it from the host (${re.bindAttributeName}="${t}: path").`);return queueMicrotask(()=>{throw e}),di}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:ri.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 li.set(n,s={el:n,pe:t,state:d,engine:0===a.length?null:a[0].engine,entries:h,C:null}),d}(e,n,s,!i):Promise.reject(new Error(`[@wcstack/state] "bind-component" requires <${re.tagNames.state}> to be a direct child of a custom element.`))).catch(l),async start(t,n){await Ri(e,s,i?r:s,t,()=>{a=!0,n()}).catch(e=>{let t=o();return!a&&null!==t&&(t.broken=!0),l(e)})},Ge(){let t=o();null!==t?Hi(t).catch(e=>console.error(e)):a?Promise.resolve().then(()=>{if(e.parentNode===r)return Ri(e,s,i?r:s,li.get(s).state,()=>{})}).catch(e=>console.error(e)):si.has(s)&&vi(s)},Ln(){let e=o();null!==e&&(xi(e,!1),!e.broken&&(e.R.Se("$disconnectedCallback"),null===e.host.engine&&c.element?.(e.R,"disconnected")))},reset(){v(`re-setting a component's state is not supported: write <${s?.localName}>.${n} instead.`)}}}var Di={name:"scopes",install(){c.ct=d(m,c.ct,Xr),c.ct=d(m,c.ct,ti),c.ct=d(m,c.ct,Wi),c.ar=gi,c.Eo=yi,c.element=h(c.element,(e,t)=>{if("mounting"!==t)return function(e,t){let n=Rr.get(e)??[];if("disconnected"===t)for(let e of n)Br(e);else if("reset"!==t&&zr(It.get(e.root))===e){qr(e,e.root);for(let e of n)Mr.get(e.root).has(e.t)||Mr.get(e.root).set(e.t,e)}}(e,t);let n=e.element.getRootNode();qr(e,n),function(e,t){let n=t.host,r=void 0===n?void 0:Yr.get(n);void 0!==r&&Zr.set(e,{host:n,def:r})}(e,n)}),c.ve=h(c.ve,(e,t,n,r,i,s)=>{(function(e,t,n,r){let i=Zr.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),ji(e,t,n,r,i,s,!1)}),c.ke=h(c.ke,(e,t,n)=>ji(e,t,n,void 0,void 0,!1,!0)),c.Oe=d(f,c.Oe,(e,t,n,r,i)=>(function(e,t){let n=Rr.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=ai.get(e);if(void 0===i)return!1;for(let e=t;null!==e&&void 0===r;e=e.d)r=i.ft.get(e);if(void 0===r)return!1;let s=r.e;return!((null===s.r||s.r.w)&&!s.ro)&&(!!n||(Ei(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=Rr.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=ui.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)}}},Ui="$recursion",zi=new WeakMap,Fi=new WeakSet,qi=new WeakSet,Bi=0,Gi=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ki=e=>`[wcs/recursion-${e}]`;function Vi(e,t){let n=n=>v(`${Ki("declaration-invalid")} ${Ui} ${e} "${String(t)}" ${n}`);("string"!=typeof t||""===t)&&v(`${Ki("declaration-invalid")} ${Ui} ${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 Ji=(e,t)=>`${e.l}.*${e.step.repeat(t)}`;function Qi(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 Xi(e,t,n){let r=Qi(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.`),Ji(e,i.k)+r}function Yi(e,t,n){let r=new Set,i=new Set,s=(e,n,s)=>!(!Array.isArray(e)||0===e.length||(r.has(e)&&v(`${Ki("cycle")} "${n}" is reachable from itself: the data under "${t.l}" must be a tree.`),i.has(e)&&v(`${Ki("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(`${Ki("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(`${Ji(t,l)}.${t.key}`),u=e.read(i,a);s(u,i.t,l+1)&&(r.add(u),o(e.He(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.He(null,l).f,0))}function Zi(e,t){let n=function(e){let t=e[Ui],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&&D(n[0][0]),null;(null===t||"object"!=typeof t||Array.isArray(t))&&v(`${Ki("declaration-invalid")} ${Ui} must be an object mapping one anchor path to its repeating sub-path.`);let i=Object.entries(t);1!==i.length&&v(`${Ki("declaration-invalid")} ${Ui} must declare exactly one anchor (it declares ${i.length}).`);let s=Vi("anchor",i[0][0]),o=Vi("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(`${Ki("declaration-invalid")} "${e}": a recursive key is a getter without a setter.`),c.set(n,t.get),h.push([new RegExp(`^${Gi(s)}((?:${Gi(u)})*)${Gi(n)}$`),n])}return{l:l,step:u,key:a,families:c,matchers:h,owners:new Map,nodeList:new RegExp(`^${Gi(l)}((?:${Gi(`.*.${a}`)})*)$`)}}(t),r=zi.has(e);null!==n?(r||Bi++,zi.set(e,n),qi.add(e),Fi.has(e)||function(e){Fi.add(e);let t=e,n=t.nt;t.nt=r=>{let i=zi.get(e);if(r.t.includes("**")){let t=e.I.jt(r.t)===r;return void(qi.has(e)||void 0===i&&t?r.getter=()=>D(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.Le++),i.owners.set(r,i.l+".**"+n);break}n.call(e,r)};let r=t.resolve;t.resolve=(t,n)=>{let i=zi.get(e);return r.call(e,void 0!==i&&t.includes("**")?Xi(i,t,n):t,n)};let i=t.getAll;t.getAll=(n,r)=>{let s=zi.get(e);if(void 0===s||!n.includes("**"))return i.call(e,n,r);if(void 0===r)return i.call(e,Xi(s,n,t.u));(!Array.isArray(r)||r.length>0)&&v(`${Ki("getall-form")} $getAll("${n}", indexes) with "**" takes either no indexes (this depth) or [] (every depth).`);let o=Qi(s,n),l=[];return Yi(e,s,(t,n)=>{for(let r of i.call(e,Ji(s,t)+o,e.H(n)))l.push(r)}),l};let s=t.yn;t.yn=(n,r,i,o)=>{let l=zi.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(`${Ki("setall-form")} $setAll("${n}", indexes, …) with "**" takes no partial prefix: pass [] to write every node.`),("function"==typeof i||!0===o?.spread)&&v(`${Ki("setall-form")} $setAll("${n}", [], value) with "**" takes a plain value (no mapper, no spread).`),t.Be>0&&_(8);let a=Qi(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(`${Ki("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(`${Ki("readonly")} "${n}" writes into the recursive getter "${l.l}.**${e}".`)}let h=[];Yi(e,l,(e,t)=>h.push([e,t]));let d=0;for(let[t,n]of h)d+=s.call(e,Ji(l,t)+a,e.H(n),i);return d}}(e)):r&&(zi.delete(e),Bi--)}function es(e,t){if(0===Bi)return!1;let n=zi.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(`${Ki("readonly")} "${t.t}" writes into the recursive getter "${r}".`)}return!1}var ts={name:"recursion",install(){c.de=h(c.de,Zi),c.element=h(c.element,(e,t)=>{("mounting"===t||"reset"===t)&&function(e){qi.delete(e)}(e)}),c.Oe=d(f,c.Oe,es)}},ns="4.3.0",rs=e=>e.split(".").slice(0,2).join("."),is=class extends Qt{static find(e){return e.querySelector?.(re.tagNames.ssr)??null}get version(){return this.getAttribute("version")??""}get stateData(){let e=this.querySelector('script[type="application/json"]');return null===e?{}:JSON.parse(e.textContent||"{}")}get templates(){let e=new Map;for(let t of Array.from(this.children))"template"===t.localName&&e.set(t.id,t);return e}get hydrateProps(){return{}}getTemplate(e){return this.templates.get(e)??null}verifyVersion(){return rs(this.version)===rs(ns)}};function ss(e){let t=re.tagNames.ssr;void 0===e.get(t)&&e.define(t,class extends is{})}var os=()=>re.tagNames.ssr,ls=Symbol.for("wcstack.ssr.snapshotBuilder"),as=()=>!0===document.documentElement?.hasAttribute("data-wcs-server"),us=e=>document.createComment(e),cs=(e,t)=>null!==e&&8===e.nodeType&&e.data===t,hs=(e,t)=>null!==e&&8===e.nodeType&&e.data.startsWith(t),ds=new WeakMap,fs=new WeakMap,ps=new WeakMap,ms=new WeakSet,gs=new WeakMap;function ys(e,t){let n=[];for(let r=e;null!==r&&(n.push(r),r!==t);r=r.nextSibling);return n}function bs(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 vs=e=>{let t=e.nextSibling;return 1!==e.nodeType||"a"!==t?.localName||!t.hasAttribute("data-wcs-ssr-link")&&e.anchorElement!==t?null:t};function ws(e,t,n,r){let i=us(null===r?"wcs-[":`wcs-[:${r}`),s=us("wcs-]");n.length>0&&n[0].xe().before(...ys(e,t)),t.after(i);for(let e of n)null===r&&e.xe().before(us("wcs-|"));let o=n.length>0?(e=>null===e.L?e.at:e.L[e.L.length-1])(n[n.length-1]):i;(vs(o)??o).after(s);for(let e of ys(i,s))ms.add(e)}function _s(e){if(e instanceof lt){ws(e.S,e.S,e.Pe,null);for(let t of e.Pe)$s(t);return}let t=e.C;null!==t&&(ws(e.K[e.y].S,e.K[e.K.length-1].S,[t],e.y),$s(t))}function $s(e){if(null!==e.c)for(let t of e.c)_s(t)}var ks=new Set(["script","style","template","textarea","title"]),Ss="data-wcs-raw",Ns=e=>ks.has(e.localName)||e.localName===os();function Es(e){for(let t of Array.from(e.childNodes))3===t.nodeType?""===t.data?t.replaceWith(us("wcs-e")):null!==t.nextSibling&&3===t.nextSibling.nodeType&&t.after(us("wcs-s")):1===t.nodeType&&!Ns(t)&&Es(t)}var As=0;function Cs(e,t){let n=e.getRootNode(),r=[t];for(let e of fs.get(n)??[])e!==t&&!0===e.element?.hasAttribute("bind-component")&&r.push(e);let i=new Map;for(let e of r){let t=ds.get(e);if(void 0===t)continue;let n=new Map;for(let t of e.oe.values())if(null!==t.N&&n.set(t.N.S,t.N),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.j)for(let t of e.j.K)n.set(t.S,e.j);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),_s(t))}}for(let e of Array.from(n.querySelectorAll("*"))){let t=ps.get(e);if(void 0!==t){let n=document.createTreeWalker(e,133,{acceptNode:e=>ms.has(e)||1===e.nodeType&&t.has(e)&&Ms(e)?2:1}),r=[];for(let e=n.nextNode();null!==e;e=n.nextNode()){let n=e.previousSibling;(3===e.nodeType?e.data.includes("{{")&&!(Ns(e.parentNode)?gs.has(e):t.has(n)&&hs(n,"wcs-t:"))&&(gs.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);Ns(e)&&n.some(e=>gs.has(e))&&e.setAttribute(Ss,n.map(e=>gs.has(e)?`{{ ${gs.get(e)} }}`:8===e.nodeType?`\x3c!--${e.data}--\x3e`:e.textContent).join(""))}Es(9===n.nodeType?n.body:n);let s=document.createElement(os());s.setAttribute("version",ns);let o=document.createElement("script");o.type="application/json",o.textContent=function(e){return JSON.stringify(e).replace(/[<>&\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`)}(function(e){let t={};for(let n of Object.keys(e)){if("$"===n[0])continue;let r=Object.getOwnPropertyDescriptor(e,n);void 0!==r.get||void 0!==r.set||"function"==typeof r.value||(t[n]=r.value)}return t}(t.target)),s.append(o);for(let[e,t]of i){if(!e.isConnected)continue;let n=e.parentNode;for(;null!==n&&"svg"!==n.localName&&"foreignObject"!==n.localName;)n=n.parentElement;let r="svg"===n?.localName,i=`wcs-${r?"s":"t"}${As++}`;e.replaceWith(us(`wcs-p:${i}`));let o=document.importNode(xt(t),!0);for(let e of Array.from(o.querySelectorAll("template")))"http://www.w3.org/2000/svg"===e.namespaceURI&&e.replaceWith(bs(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(bs(t,l,o))}e.before(s)}function xs(e){!function(e){if(null!==e.querySelector(re.tagNames.state))for(let t of Array.from(e.querySelectorAll("input,textarea,select")))if("select"===t.localName){let e=Array.from(t.options);if(t.multiple||e.some(e=>e.hasAttribute("selected"))||e[t.selectedIndex]!==e.find(e=>!e.disabled))for(let t of e)t.toggleAttribute("selected",t.selected)}else"textarea"===t.localName?t.value!==t.defaultValue&&!t.value.includes("{{")&&!Array.from(t.childNodes).some(e=>gs.has(e))&&(t.textContent=t.value):"checkbox"===t.type||"radio"===t.type?t.toggleAttribute("checked",t.checked):"password"!==t.type&&t.value!==t.defaultValue&&t.setAttribute("value",t.value)}(e);for(let t of Array.from(e.querySelectorAll(`${re.tagNames.state}[enable-ssr]`))){if(t.hasAttribute("mount")||t.hasAttribute("bind-component")||t.previousElementSibling?.localName===os())continue;let e=t.engine;null!=e&&Cs(t,e)}}var Ts=Symbol.for("wcstack.state.ssr.impl"),Ps=new Map,Os=new WeakMap,Ms=e=>!0===c.Eo?.(e),Ls=e=>1===e.nodeType&&!Ns(e)&&!Ms(e),Is=e=>e.f.flat().concat(e.z??[]),js=e=>{for(let t of Is(e))t.remove()};function Rs(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&&!cs(l,"wcs-]");){let e=l.nextSibling;if(cs(l,"wcs-|"))o.push([]),l.remove();else{0===o.length&&o.push([]);let n=o[o.length-1];hs(l,"wcs-[")?e=Rs(l,t,n):(n.push(l),Ls(l)&&Hs(l,t))}l=e}let a={branch:void 0===r[1]?null:Number(r[1]),f:o,z:l??s.appendChild(us("wcs-]"))},u=Is(a);l=a.z.nextSibling;for(let e of u)n?.push(e),t&&Et.add(e);return t&&null!==i?Ps.set(i,a):js(a),l}function Hs(e,t){for(let n=e.firstChild;null!==n;)hs(n,"wcs-[")?n=Rs(n,t):(Ls(n)&&Hs(n,t),n=n.nextSibling)}function Ws(e,t,n){let r=e=>{for(let i of Array.from(e.childNodes))if(i.parentNode===e)if(8===i.nodeType){let e=i.data;try{if("wcs-s"===e)i.remove();else if("wcs-e"===e)i.replaceWith("");else if(e.startsWith("wcs-t:")){let t=us(`@@:${decodeURIComponent(e.slice(6))}`),n=i.nextSibling;for(;null!==n&&!cs(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]?bs(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&&!Ns(i)&&(Ms(i)?Os.set(i,{ssr:t,Ie: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||Gs(n)||"template"===n.localName);n=n.previousSibling)e.unshift(n);let n=0,r=0;if(e.forEach((e,t)=>{hs(e,"wcs-[")?r++:cs(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(hs(r,"wcs-["))i++;else if(cs(r,"wcs-]")&&0===i--){t.prepend(...e.slice(n));break}}}(e),Hs(e,n)}function Ds(e){let t=Os.get(e);if(void 0===t||(Os.delete(e),Ws(e,t.ssr,t.Ie),!t.Ie))return null;let n=c.Ie;return c.Ie=Js,()=>{c.Ie=n,Us()}}function Us(){for(let e of Ps.values())js(e);Ps.clear()}function zs(e){let t=[];for(let n=document.createTreeWalker(e,128);n.nextNode();)t.push(n.currentNode);return t}function Fs(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 qs(e,t,n){if(as()){if(n instanceof Array){for(let e=n.length;e-- >0;)gt(n[e])&&n.splice(e,1);let e=t;if(n.some(yt))ms.add(e);else if(e.localName.includes("-")&&!Ms(e)){let t=new Map;for(let n=document.createTreeWalker(e,133);n.nextNode();)t.set(n.currentNode,n.currentNode.data);ps.set(e,t)}return}if("string"==typeof n){if(gs.set(t,n),Ns(t.parentNode))return;let e=us(`wcs-t:${encodeURIComponent(n)}`),r=us("wcs-/t");return t.before(e),void t.after(r)}let r=ds.get(e);void 0===r&&ds.set(e,r=new Map),r.set(t,n);let i=t.getRootNode(),s=fs.get(i);return void 0===s&&fs.set(i,s=new Set),void s.add(e)}if("string"!=typeof n&&Ps.size>0){let e=Ps.get(n);void 0!==e&&(Ps.delete(n),Ps.set(t,e))}}var Bs=e=>null!==e&&8===e.nodeType&&[re.commentIfPrefix,re.commentElseIfPrefix,re.commentElsePrefix].includes(e.data),Gs=e=>3===e.nodeType&&""===e.data.trim(),Ks=e=>{let t=Ps.get(e)?.z??e;return(vs(t)??t).nextSibling};function Vs(e,t){if(t.length!==e.ln.childNodes.length)return!1;let n=e.On;for(let r=0;r<n.length;r++){let i=n[r],s=e.ln,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=(vs(o)??o).firstChild;for(let t=i[e];t>0&&null!==o;t--)o=Ks(o)}e.ko[r]=o}return!0}function Js(e,t,n){if(0===Ps.size)return null;let r=t,i=0;if(!n){let e=re.commentIfPrefix;if(!cs(t,e))for(let n=t.previousSibling;null!==n&&1!==n.nodeType&&(Bs(n)&&i++,!cs(n,e));n=n.previousSibling);for(let n=t.nextSibling;!Ps.has(r)&&null!==n&&!cs(n,e)&&1!==n.nodeType;n=n.nextSibling)Bs(n)&&(r=n)}let s=Ps.get(r);if(void 0===s)return null;if(!n&&s.branch!==i)return Ps.delete(r),js(s),null;let o=s.f.shift();if(0===s.f.length&&Ps.delete(r),s.z?.replaceWith(...ys(t,r)),s.z=null,void 0===o)return null;let l=[];for(let e=0;e<o.length;e++){let t=Ps.get(o[e]);if(l.push(o[e]),void 0!==t)for(;e<o.length&&o[e]!==t.z;)e++;else vs(o[e])===o[e+1]&&e++}if(!Vs(e,l)){let n=(e.In?e.root:e.ln).cloneNode(!0);l=e.In?[n]:[...n.childNodes],Vs(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 Qs={name:"ssr",install(){c.jn=qs,c.hr=Ds;let e=c.element;c.element=(t,n)=>{"mounting"===n&&function(e){let t=e.element;if(!t.hasAttribute("enable-ssr")||as())return;let n=t.previousElementSibling,r=n?.localName===os(),i=r?n.getAttribute("version"):null,s=null===i||rs(i)===rs(ns);if(s){let t=e,n=t.Se;t.Se=(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] <${os()} version="${i}"> does not match ${ns}: its snapshot is discarded, and the page renders on the client from its own state.${o&&!a?" 3.x output keeps only the path of a text binding outside a template, so such a binding loses its filters: deploy @wcstack/server 4.0 with this client.":""}`);let u=s?n.querySelector('script[type="application/json"]'):null;if(null!==u){let t=JSON.parse(u.textContent||"{}"),n=e.target;for(let e of Object.keys(t)){let r=Object.getOwnPropertyDescriptor(n,e);void 0!==r&&(void 0!==r.get||void 0!==r.set||"function"==typeof r.value)||(n[e]=t[e])}e.hydrated=!0}let h=t.getRootNode();for(let e of Array.from(h.querySelectorAll(`[${Ss}]`)))e.textContent=e.getAttribute(Ss),e.removeAttribute(Ss);let d=9===h.nodeType?h.body:h;queueMicrotask(function(e){let t=[];for(let n of Array.from(e.querySelectorAll("input,textarea,select")))if("select"===n.localName){let e=Array.from(n.options),r=e.map(e=>e.selected),i=e.map(e=>e.hasAttribute("selected")),s=i.lastIndexOf(!0);s<0&&(s=e.findIndex(e=>!e.disabled)),(n.multiple?e.some((e,t)=>r[t]!==i[t]):n.selectedIndex!==s)&&t.push([n,()=>e.forEach((e,t)=>e.selected=r[t])])}else if("checkbox"===n.type||"radio"===n.type){let e=n.checked;e!==n.defaultChecked&&(e||"checkbox"===n.type)&&t.push([n,()=>n.checked=e])}else if("file"!==n.type&&n.value!==n.defaultValue){let e=n.value;t.push([n,()=>n.value=e])}return()=>{for(let[e,n]of t)e.isConnected&&(n(),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})))}}(d)),o?function(e,t,n){let r=new Map,i=e=>{let t=e.parentElement;for(;null!==t&&!Ms(t);)t=t.parentElement;if(null===t)return null;let n=r.get(t);if(void 0===n){let e=i(t),s=t.querySelector(`:scope > ${re.tagNames.state}[bind-component]`).getAttribute("bind-component");r.set(t,n=[]);for(let r of ae(t.getAttribute(re.bindAttributeName)??"")){let t=r.Qe;r.$e[0]===s&&n.push([e?Fs(e,t,1,0):t,r.$e.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:Fs(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]:Fs(r,s[2],2,1)??s[2]};for(let t of zs(e).reverse()){let e=/^@@wcs-(\w+)-start:([\s\S]*)/.exec(t.data);if(null===e)continue;let r=t.nextSibling;for(;null!==r&&!cs(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]?[us(`@@:${s(t,e[2],n)}`)]:[])}}let o=(e,n)=>{for(let r of zs(e)){let e=/^@@wcs-(?:for|if|elseif|else):(\S+)$/.exec(r.data)?.[1],i=Array.from(t.querySelectorAll("template")).find(t=>t.id===e);if(void 0===i)continue;let l=document.importNode(i,!0),a=re.bindAttributeName;l.removeAttribute("id"),l.setAttribute(a,l.getAttribute(a).replace(/^(\s*\w+\s*:\s*)([^\s|]+)/,(e,t,i)=>t+s(n??r,i))),o(l.content,n??r);let u=l.content.firstChild;r.replaceWith(.../^\s*elseif\s*:/.test(u?.getAttribute?.(a)??"")?l.content.childNodes:[l])}};o(e);for(let t of Array.from(e.querySelectorAll("[data-wcs-ssr-id]")))t.removeAttribute("data-wcs-ssr-id")}(d,n,a):Ws(d,n,s),n.remove(),s&&(c.Ie=Js,queueMicrotask(()=>{Us(),c.Ie=null}))}(t),e?.(t,n)},function(){let e=globalThis;e[Ts]={build:xs,reset(){As=0}},void 0===e[ls]&&(e[ls]={protocol:"wcs-ssr-snapshot",version:1,build:t=>e[Ts].build(t),reset:()=>e[Ts].reset()})}(),c.To=h(c.To,ss);for(let e of Zt())ss(e)}},Xs="__WCSTACK_DEVTOOLS_HOOK__",Ys=null,Zs=new Set,eo=(e,t,n)=>({absolutePathInfo:{pathInfo:{path:t.t},stateElement:e.element},listIndex:null===n?null:{indexes:e.H(n)}}),to=new WeakMap,no=0,ro=new WeakMap;function io(e){if(null===Ys)return;let t=ro.get(e),n=Zs.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=to.get(e);return void 0===t&&to.set(e,t=++no),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:eo(e,o,c)})},s=e=>i(e.i,e.name,e.a,e.o,e.r,e.on()),o=e=>{if(!r.has(e)){if(r.add(e),null!==e.he)for(let t of e.he)s(t);if(e instanceof Xe&&null!==e.fe){let t=e.O.Ye;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 lt){i(-1,"for",e.S,e.l.o,e.l.ae,"for");for(let t of e.Pe)o(t)}else null!==e.C&&o(e.C)};for(let t of e.ce.values())for(let e of t)s(e),null!==e.j&&l(e.j);for(let t of e.oe.values())if(null!==t.N&&l(t.N),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)||Ys({type:"state:binding-removed",...r});for(let[e,r]of n)(void 0===t||!t.has(e))&&Ys({type:"state:binding-added",...r});ro.set(e,n)}function so(e){let t=It.get(e);if(void 0===t)throw new Error("[@wcstack/state] devtools: no state tree on this root");return t}function oo(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.Ae.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 lo=new WeakSet,ao=new WeakMap;function uo(e,t){if(("mounting"===t||"reset"===t)&&function(e){let t=(t,n)=>{if(lo.has(t))return;lo.add(t);let r=t.emit;t.emit=(...i)=>(null!==Ys&&Ys({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.Ae.values())t(n,"event")}(e),"connected"===t){if(Zs.has(e))return;Zs.add(e),Ys?.({type:"state:element-registered",rootNode:e.root,element:e.element}),io(e)}else"disconnected"===t&&(Zs.delete(e),io(e),Ys?.({type:"state:element-unregistered",rootNode:e.root,element:e.element}))}function co(e,t,n,r,i,s){if(null===Ys)return;let o=eo(e,t,0===t.n?null:n),l=ao.get(e);void 0===l&&ao.set(e,l=new Set),l.add(o),s&&Ys({type:"state:write",absoluteAddress:o,value:i,oldValue:r,hasOldValue:!0})}function ho(e){if(null===Ys)return;let t=ao.get(e);ao.delete(e),void 0!==t&&Ys({type:"state:update-batch",addresses:t}),io(e)}function fo(e,t,n){Ys?.({type:"state:binding-apply-error",path:n.o.t,bindingType:n.on(),error:t})}var po={"*":["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 mo(e,t){let n=e.localName;if(n.includes("-"))return null;let r=(e=>[...po["*"],...Object.hasOwn(po,e)?po[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())}([vn,Zn,Sr,Or,Di,ts,Qs,{name:"devtools",install(){c.element=h(c.element,uo),c.ve=h(c.ve,co),c.Ce=h(c.Ce,ho),c.ze=h(c.ze,fo),function(){if(typeof document>"u"||document.documentElement?.hasAttribute("data-wcs-server"))return;let e=globalThis,t=e[Xs]??(e[Xs]=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:ns,getStateElements:()=>[...Zs].map(oo),overlays:()=>[],keyedSubscriptions:e=>function(e){let t=[];for(let n of e.I.all()){let r=n._,i=n.De?.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}(so(e)),keys(e){let t=so(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 so(e).element.createState("readonly",e=>{r=e.$resolve(t,n??[])}),r},write(e,t,n,r){so(e).element.createState("writable",e=>{e.$resolve(t,r??[],n)})},_setSink(e){let t=null===Ys&&null!==e;Ys=e,null===e&&(ro=new WeakMap),c.st=e&&((e,t)=>Ys?.({...t,stateElement:e.element})),t&&queueMicrotask(()=>{for(let e of Zs)io(e)})}})}()}},{name:"native-commands",install(){c.or=mo}}]),function(e=customElements){(function(){let e=globalThis;void 0===e[Wt]&&(e[Wt]={protocol:"wcs-binder",version:1,bind:Ft})})(),Zt().includes(e)||Yt.push(new WeakRef(e));let t=re.tagNames.state;void 0===e.get(t)&&e.define(t,class extends Xt{}),c.To?.(e)}();const go={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"},yo=!1,bo=[".html"];function vo(){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 wo(e,t){if(t&&"cause"in t)throw new Error(`[@wcstack/router] ${e}`,{cause:t.cause});throw new Error(`[@wcstack/router] ${e}`)}let _o=class extends Error{fallbackPath;constructor(e,t){super(e),this.fallbackPath=t}};const $o={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 ko(e){const t={};for(const[n,r]of new URLSearchParams(e))t[n]=r;return Object.freeze(t)}function So(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 No={static:2,param:1,"catch-all":0};let Eo=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&&wo(`${go.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&wo(`${go.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+=No[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($o).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=!1,t.hasGuard&&(this._guardFallbackPath=t.guardFallback||"/",this.enableGuard())}enableGuard(){this._hasGuard||(this._hasGuard=!0,this._guardFallbackPath||="/",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||wo(`${go.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:ko(e.search??""),routeName:e.routes[e.routes.length-1]?.name??""})}(e));if("string"==typeof r&&""!==r)throw new _o("Navigation cancelled by guard.",r);if(!r)throw new _o("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof r?r:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new _o("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}};const Ao="data-wcs-ssr",Co="data-wcs-ssr-link",xo="@@wcs-route-ph:",To="@@wcs-route-start:",Po="@@wcs-route-end:";let Oo=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=vo();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new Eo(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||wo(`${go.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(`${Po}${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()}enableGuard(){this._core.enableGuard()}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):wo(`${go.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&&wo(`${go.route} with fallback attribute must be a direct child of ${go.router}.`),e.fallbackRoute&&wo(`${go.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 Mo=Symbol.for("wcstack.trustedTypes.policy"),Lo=Symbol.for("wcstack.trustedTypes.internal"),Io="wcstack";function jo(){const e=globalThis[Mo];return null===e||"object"!=typeof e?null:e}let Ro=!1;function Ho(e){const t=function(){const e=globalThis,t=e[Lo];if(void 0!==t)return t;const n=globalThis.trustedTypes;let r=null;if(n&&"function"==typeof n.createPolicy)try{r=n.createPolicy(Io,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){"function"!=typeof jo()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${Io}". Allow it in the CSP (\`trusted-types ${Io};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,e)}return e[Lo]=r,r}(),n=t?.createHTML;if("function"==typeof n)return n.call(t,e);if(!("trustedTypes"in globalThis))return e;const r=jo(),i=r?.createHTML;return"function"==typeof i?(Ro||(Ro=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${Io}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${Io};\` in the CSP to avoid this. See docs/csp.md section 7.`)),i.call(r,e)):e}const Wo=new Map;let Do=class extends HTMLElement{_uuid=vo();constructor(){super()}async _loadTemplateFromSource(e){try{const t=await fetch(e);t.ok||wo(`${go.layout} failed to fetch layout from source: ${e}, status: ${t.status}`);const n=await t.text();return Wo.set(e,n),n}catch(t){wo(`${go.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(`${go.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(e)Wo.has(e)?n.innerHTML=Ho(Wo.get(e)||""):n.innerHTML=Ho(await this._loadTemplateFromSource(e)||"");else if(t){const e=this._loadTemplateFromDocument(t);e?n.innerHTML=Ho(e):console.warn(`${go.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")&&yo}get name(){return this.getAttribute("name")||""}},Uo=class extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||wo(`${go.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")&&yo}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}};const zo=new Set(["props","states","attr",""]);function Fo(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 qo(e,t){e.hasAttribute("data-bind")||wo(`${e.tagName} has no 'data-bind' attribute.`);const n=e.getAttribute("data-bind")||"";zo.has(n)||wo(`${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&&Fo(e,t,r)}).catch(()=>{wo(`Failed to define custom element: ${i}`)}):Fo(e,t,r)}const Bo=Symbol.for("wcstack.binder");function Go(){const e=globalThis[Bo];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}const Ko=Symbol.for("wcstack.binder.pending"),Vo=Symbol.for("wcstack.binder.taken");function Jo(){const e=globalThis;let t=e[Vo];return void 0===t&&(t=new WeakSet,e[Vo]=t),t}function Qo(e,t){const n=Go();return null===n?(function(){const e=globalThis;let t=e[Ko];return void 0===t&&(t=[],e[Ko]=t),t}().push(e),!1):(Jo().add(e),n.bind(e,t),!0)}const Xo={range:!0};function Yo(e,t){for(const n of e.routeChildNodes)t.add(n.placeHolder).add(n.endMarker),Yo(n,t);return t}function Zo(e){const t=e.placeHolder,n=e.endMarker,r=null!==n.parentNode&&n.parentNode===t.parentNode&&!!(4&t.compareDocumentPosition(n)),i=r?null:Yo(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}const el=new WeakSet;function tl(e){const t=go.router,n=go.outlet;for(const r of e.querySelectorAll(n))el.has(r)||r.previousElementSibling?.matches(t)||(el.add(r),console.warn(`[@wcstack/router] [wcs/router-outlet-misplaced] A <${t}> uses only the element right after it as its outlet, and this page has a <${n}> that no router uses. The router makes an outlet of its own right after itself, so the routes render there and the <${n}> you placed stays empty. Move the <${n}> right after the <${t}>.`,r))}const nl=e=>{for(const t of e)if(t.nodeType===Node.ELEMENT_NODE||t.nodeType===Node.TEXT_NODE&&""!==t.textContent.trim())return!0;return!1};function rl(e){console.warn(`[@wcstack/router] [wcs/layout-slot-missing] This layout's template has no default <slot>, so what its <${go.layout}> holds outside the named slots — the nested routes and their pages — is not shown. Put a <slot></slot> where the page goes.`,e)}class il extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||wo(`${go.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));const t=[];for(const e of Array.from(this.layout.childNodes))this._layoutChildNodes.push(e),e instanceof Element&&e.getAttribute("slot")||t.push(e),this.appendChild(e);!this.shadowRoot.querySelector('slot:not([name]), slot[name=""]')&&nl(t)&&rl(this),tl(this.shadowRoot)}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(`${go.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):nl(i.childNodes)&&rl(this),this.appendChild(t),tl(this)}!function(e){if(null!==Go())for(const t of e)1===t.nodeType&&Qo(t,Xo)}(Array.from(this.childNodes))}finally{this._initializing=!1}}async connectedCallback(){null!==this._layout&&(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=>{qo(t,e)}),t.hasAttribute("data-bind")&&qo(t,e))}}function sl(){return document.createElement(go.layoutOutlet)}const ol="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function ll(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)),wo(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 ${ol}`:`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 ${ol}`}(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:(console.error(`${go.guardHandler}: the <script type="module"> has no default-exported function, so the route's guard redirects every navigation.`),t.notifyGuardHandlerLoadFailed())}).catch(e=>{console.error("loadGuardHandler failed:",e),t.notifyGuardHandlerLoadFailed()})}function al(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 ul(e,t,n,r){const i=document.createDocumentFragment();let s=null;const o=Array.from(t.childNodes);for(const t of o)if(t.nodeType===Node.ELEMENT_NODE){let o=t,l=t,a=n;const u=l.tagName.toLowerCase();if(u===go.route){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const i=document.importNode(l,!0);customElements.upgrade(i),i.appendChild(t);const u=i;u.initialize(e,n),al(r,u),o=u.placeHolder,l=u,a=u,s=u}else{if(u===go.guardHandler){const e=n??s,t=l.querySelector('script[type="module"]');null===e?console.error(`[@wcstack/router] [wcs/guard-handler-ignored] A <${go.guardHandler}> outside a <${go.route}> guards nothing: put it inside the route it guards.`):t?(null===n&&console.error(`[@wcstack/router] [wcs/guard-handler-ignored] A <${go.guardHandler}> outside a <${go.route}> guards the route before it, "${e.absolutePath}": put it inside that route.`),e.enableGuard(),ll(t,e)):console.error(`[@wcstack/router] [wcs/guard-handler-ignored] The <${go.guardHandler}> of route "${e.absolutePath}" has no <script type="module">, so the route is not guarded.`);continue}if("template"===u){i.appendChild(l);continue}if(u===go.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=sl();r.layout=n,o=r,l=t}}const c=await ul(e,l,a,r);l.replaceChildren(),l.appendChild(c),i.appendChild(o)}else i.appendChild(t);return i}async function cl(e){const t=new Map;return await ul(e,e.template.content,null,t)}function hl(e){return!1!==e.checkVisibility?.()}function dl(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=$o[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)dl(i,t,n,r)}function fl(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)dl(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 pl=null,ml=null;function gl(){const e=bo;return 0===e.length?null:(pl===e&&ml||(pl=e,ml=new RegExp(`\\/[^/]+(?:${e.map(e=>e.replace(/\./g,"\\.")).join("|")})$`,"i")),ml)}function yl(e){let t=e||"/";t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/");const n=gl();return n&&(t=t.replace(n,"")),""===t&&(t="/"),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function bl(e,t){let n=e;return""!==t&&(e===t?n="":e.startsWith(t+"/")&&(n=e.slice(t.length))),""===n?"/":n}function vl(e){let t=e||"";if(!t)return"";t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/");const n=gl();return n&&(t=t.replace(n,"")),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),"/"===t?"":t}function wl(e){if(null!==e.held)return;const t=Zo(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 _l(e){e.clearParams(),wl(e)}function $l(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=>{qo(t,e.typedParams)}),n.hasAttribute("data-bind")&&qo(n,e.typedParams),n.querySelectorAll(go.layoutOutlet).forEach(t=>{t.assignParams(e.typedParams)}),n.tagName.toLowerCase()===go.layoutOutlet&&n.assignParams(e.typedParams)}}const kl=new WeakSet;function Sl(e){const t=e.placeHolder;null!==t.parentNode&&(kl.has(e)||null!==e.endMarker.parentNode?(wl(e),t.after(e.held),e.held=null):t.after(...e.childNodeArray,e.endMarker),kl.add(e))}const Nl=Symbol.for("wcstack.transition-runner");const El=new WeakSet,Al="data-wcs";function Cl(e,t,n){!El.has(e)&&function(e){return e.hasAttribute(Al)||null!==e.querySelector(`[${Al}]`)}(e)&&(El.add(e),function(e){"complete"===document.readyState?e():window.addEventListener("load",e,{once:!0})}(()=>{var r;null!==Go()||(r=e,Jo().has(r))||console.warn(`[@wcstack/router] ${t} contains ${Al} 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 xl(e){return"AbortError"===e?.name}const Tl=new WeakMap;function Pl(e){for(const t of e.childNodeArray)if(1===t.nodeType){if(t.isConnected){if(Qo(t,Xo))continue}else if(null!==Go())continue;Cl(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 Ol(e,t){try{let n=null;for(const e of t.routes){const r=await e.guardCheck(t);r&&(n=null===n?r:Object.assign({},n,r))}t.data=n,Tl.delete(e)}catch(n){if(n instanceof _o){const r=(Tl.get(e)??0)+1;return r>10?(Tl.delete(e),console.error(`${go.router}: guard redirect loop — stopped after 10 redirects in a row (the last: ${t.path} → ${n.fallbackPath}). The guards of these routes send each other back and forth.`),!1):(Tl.set(e,r),e.connectedCallbackPromise.catch(()=>{}).then(()=>e.replace(n.fallbackPath)).catch(e=>{xl(e)||console.error("Fallback navigation failed:",e)}),!1)}throw n}return!0}async function Ml(e,t,n,r,i=""){const s=bl(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=fl(e,s);o||(e.fallbackRoute?o={routes:[e.fallbackRoute],params:{},typedParams:{},path:s,lastPath:r}:wo(`${go.router} No route matched for path: ${s}`)),o.lastPath=r,o.search=i;const l=t.lastRoutes,a=await async function(e,t,n,r){if(!await Ol(e,t))return!1;r?.();const i=new Set(t.routes),s=new Set(n),o=()=>{for(const e of n)i.has(e)||_l(e);const e=[];for(const n of t.routes)(e.length>0||!s.has(n)||n.shouldChange(t.params))&&(e.push(n),$l(n,t));let r=!1;for(const t of e){const e=s.has(t);e&&r||Sl(t),r||=e,n.length>0&&!e&&Pl(t)}};let l;return 0===n.length?o():l=function(e,t,n){const r=function(e){const t=globalThis[Nl];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",o),void 0!==l&&await l,!0}(e,o,l,()=>{e.commitNavigation({params:o.params,typedParams:o.typedParams,routeName:o.routes[o.routes.length-1]?.name??"",data:o.data??null,search:i,path:s},!0)});return!!a&&(e.releasePath(),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(hl(e))return e}else for(const t of e.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(hl(t))return t}return null}(t.routes[t.routes.length-1].childNodeArray);if(null!==e)e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1"),e.focus();else{const e=document.querySelector("[autofocus]");null!==e?e.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}(e,o),!0)}function Ll(){const e=window.navigation;return e?"function"!=typeof e.addEventListener||"function"!=typeof e.removeEventListener?null:e:null}function Il(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 jl(e){return"?"===e?"":e}function Rl(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 Hl=new WeakMap;function Wl(e,t,n){const r=function(e,t){let n=Hl.get(e);return void 0===n&&(n=new Map,Hl.set(e,n)),n.has(t)||n.set(t,e.getAttribute(t)),n.get(t)}(e,t);!function(e,t,n){null===n?e.removeAttribute(t):e.setAttribute(t,n)}(e,t,void 0===n?r:null===n?null:String(n))}function Dl(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const Ul=Object.freeze({});class zl 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"},{name:"leaveConfirm",attribute:"leave-confirm"}],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=Ul;_typedParams=Ul;_searchParams=Ul;_routeName="";_data=null;_hasCommitted=!1;_pathHeld=!1;_leaveChecked=!1;_leaveConfirmed=!1;_unloadConfirmed=!1;_listeningUnload=!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 yl(e)}_normalizeBasename(e){return vl(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}set basename(e){Wl(this,"basename",e)}get leaveConfirm(){return this.getAttribute("leave-confirm")||null}set leaveConfirm(e){Wl(this,"leave-confirm",e),this._syncBeforeUnload()}_onBeforeUnload=e=>{null===this.leaveConfirm||this._unloadConfirmed||e.preventDefault()};_syncBeforeUnload(){const e=this.isConnected&&null!==this.leaveConfirm&&!Dl();e!==this._listeningUnload&&(this._listeningUnload=e,e?window.addEventListener("beforeunload",this._onBeforeUnload):window.removeEventListener("beforeunload",this._onBeforeUnload))}_confirmLeave(e){const t=this.leaveConfirm;return!(null!==t&&this._hasCommitted&&!this._leaveConfirmed&&!this.isSameMatch(bl(this._normalizePathname(e),this._basename)))||(this._leaveConfirmed=window.confirm(t))}_confirmUnload(e){const t=this.leaveConfirm;null!==t&&!1!==e.cancelable&&this._hasCommitted&&!this._unloadConfirmed&&(window.confirm(t)?(this._unloadConfirmed=!0,setTimeout(()=>{this._unloadConfirmed=!1},0)):e.preventDefault?.())}_ownedByAnotherRouter(e){for(const t of document.querySelectorAll(go.router))if(t!==this&&t instanceof zl&&t._isOwnPath(e))return!0;return!1}_getOutlet(){const e=this.nextElementSibling;if(e&&e.matches(go.outlet))return e;!function(e){const t=e.getRootNode();t.nodeType!==Node.DOCUMENT_NODE&&t.nodeType!==Node.DOCUMENT_FRAGMENT_NODE||tl(t)}(this);const t=document.createElement(go.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||wo(`${go.router} has no outlet.`),this._outlet}get template(){return this._template||wo(`${go.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,t=!1){const n=Object.freeze({...e.params}),r=Object.freeze({...e.typedParams}),i=ko(e.search),s=e.data??null,o=this._data!==s,l=!So(this._params,n),a=this._routeName!==e.routeName,u=!So(this._searchParams,i),c=this._path!==e.path;o&&(this._data=s),l&&(this._params=n,this._typedParams=r),a&&(this._routeName=e.routeName),u&&(this._searchParams=i),this._path=e.path,this._hasCommitted=!0,this._leaveConfirmed=!1,o&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),l&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),a&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),u&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),this._pathHeld=c&&t,c&&!t&&this._firePathChanged()}releasePath(){this._pathHeld&&(this._pathHeld=!1,this._firePathChanged())}_firePathChanged(){this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:this._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=>{xl(e)||console.error(`${go.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=>{xl(e)||console.error(`${go.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=Il(e),r=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,i=r+jl(n.search)+n.hash;if(null!==this.leaveConfirm&&(await Promise.resolve(),!this._confirmLeave(r)))return;const s=Ll();if(s?.navigate){let e;this._leaveChecked=!0;try{e=t?s.navigate(i,{history:"replace"}):s.navigate(i)}finally{this._leaveChecked=!1}await(e?.finished)}else{t?history.replaceState(null,"",i):history.pushState(null,"",i);const e=this._normalizePathname(r),s=this.isSameMatch(bl(e,this._basename));await Ml(this,this.outlet,e,this._path,jl(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.defaultPrevented||e.hashChange||null!==e.downloadRequest)return;const t=new URL(e.destination.url),n=this._normalizePathname(t.pathname);if(!e.canIntercept||!this._isOwnPath(n))return void(e.canIntercept&&this._ownedByAnotherRouter(n)||this._confirmUnload(e));if(!this._leaveChecked&&!1!==e.cancelable&&!this._confirmLeave(n))return void e.preventDefault?.();const r=this.isSameMatch(bl(n,this._basename)),i=r&&("push"===e.navigationType||"replace"===e.navigationType),s=t.search,o=this;e.intercept({handler:async()=>{try{await Ml(o,o.outlet,n,o.path,s)}catch(e){throw console.error(`${go.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 Ml(this,this.outlet,e,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const e=Dl();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||wo(`${go.router} basename is empty, but current path is not "/".`),e||""===this._basename||t||this.getAttribute("basename")||console.warn(`[@wcstack/router] [wcs/base-href-missing] The basename "${this._basename}" was taken from this page's URL: the page has no <base href> and <${go.router}> no basename, so routes and links resolve under it, and a deep link or a reload away from the app's root shows the wrong route. Add <base href="/"> (or the app's folder) to <head>.`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||wo(`${go.router} should have a <template> child element.`);const r=e?this._template.content.cloneNode(!0):null,i=await cl(this),s=!e&&this._outlet.hasAttribute(Ao);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&&wo(`${go.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(Ao);const e=this._outlet.rootNode;for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(i)}await Ml(this,this.outlet,o,this._path,window.location.search||""),(s||null!==Go())&&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(go.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(xo)){const r=t.slice(15);if(i.has(r)||!n.has(r))return!1;i.set(r,e)}else if(t.startsWith(To)){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(Po)){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=bl(e,this._basename);let h=fl(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(To)){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()===go.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(Ao);for(const e of h.routes)$l(e,h);return this.outlet.lastRoutes=h.routes,!await Ol(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=bl(e,this._basename),n=fl(this,t),r=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===r.length&&wo(`${go.router} No route matched for path: ${t}`),!r.some(e=>e.hasGuard)){await Ml(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(e=>{e.placeHolder.data=`${xo}${e.absolutePath}`}),this.outlet.setAttribute(Ao,"");for(const e of this.outlet.lastRoutes)e.placeHolder.after(document.createComment(`${To}${e.absolutePath}`))}}_offerInitialContentToBinder(){for(const e of this.outlet.lastRoutes)for(const t of e.childNodeArray)t.nodeType===Node.ELEMENT_NODE&&t.isConnected&&Qo(t,Xo)}_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(!Rl(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this._syncBeforeUnload(),Dl()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(e){throw this._rejectConnectedCallback?.(e),e}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(e){throw this._rejectConnectedCallback?.(e),e}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const e=Ll();e&&!this._listeningNavigate&&(e.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),e||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(Ll()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),this._syncBeforeUnload(),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const Fl=["title","rel","target","download","hreflang","lang","dir"];class ql extends HTMLElement{static get observedAttributes(){return["to","match",...Fl]}_childNodeArray=[];_uuid=vo();_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(go.router);if(e)return this._router=e;const t=this.getRootNode(),n=t.querySelector?.(go.router);if(n)return this._router=n;wo(`${go.link} is not connected to a router.`)}_initialize(){Dl()||(this.style.display="none"),this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(e){return yl(e)}_joinInternalPath(e,t){const n=vl(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(""!==t)if(this._isInternalTarget(t)){const{pathname:n,search:r,hash:i}=Il(t),s=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);e.href=s+jl(r)+i}else try{e.href=new URL(t).toString()}catch{wo(`[${go.link}] Invalid URL in 'to' attribute: ${t}`)}else e.removeAttribute("href")}connectedCallback(){Dl()?queueMicrotask(()=>{if(this.isConnected)try{this._connect()}catch(e){console.error(e)}}):this._connect()}_findSsrAnchor(){const e=this.nextElementSibling;return null!==e&&"A"===e.tagName&&e.hasAttribute(Co)?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(Co),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-")||Fl.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,Dl())return this._updateActiveState(),void n.setAttribute(Co,"");Ll()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),""!==this._path&&!this._isInternalTarget(this._path)||Ll()?.navigate||(this._onClick=async e=>{e.defaultPrevented||0===e.button&&(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||this._isInternalTarget(this._path)&&(e.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},n.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){Ll()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const e=this._anchorElement;e&&(this._onClick&&(e.removeEventListener("click",this._onClick),this._onClick=void 0),e.remove(),this._anchorElement=null);for(const t of this._childNodeArray)e&&t.parentNode===e&&e.removeChild(t);this._router=null}attributeChangedCallback(e,t,n){if("match"!==e||t===n){if("to"===e&&t!==n)this._path=n||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(Fl.includes(e)){const t=this._anchorElement;t&&(null===n?t.removeAttribute(e):t.setAttribute(e,n))}}else this._updateActiveState()}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const e=this._normalizePathname(new URL(window.location.href).pathname),{pathname:t}=Il(this._path),n=this._normalizePathname(this._isInternalTarget(this._path)?""===t?window.location.pathname:this._joinInternalPath(this.router.basename,t):t),r=""!==this._path&&e===n,i=!r&&""!==this._path&&"prefix"===this.getAttribute("match")&&e.startsWith(n+"/");this._anchorElement&&(r||i?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current",r?"page":"true")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const Bl=[],Gl=new Map;let Kl=!1;const Vl=new WeakMap;class Jl extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super()}_initialize(){if(!this._initialized&&(this._initialized=!0,this._childElementArray=Array.from(this.children),!Dl())){this.style.display="none";for(const e of this._childElementArray)this.removeChild(e)}}connectedCallback(){this._initialize(),Kl||(this._captureInitialHead(),Kl=!0),Bl.push(this),this._reapplyHead()}disconnectedCallback(){const e=Bl.indexOf(this);-1!==e&&Bl.splice(e,1),this._reapplyHead()}get childElementArray(){return this._initialized||wo("Head component is not initialized yet."),this._childElementArray}_getKey(e){const t=Vl.get(e);if(void 0!==t)return t;const n=this._computeKey(e);return Vl.set(e,n),n}_computeKey(e){const t=e.tagName.toLowerCase();if("title"===t)return"title";if("meta"===t)return`meta:${e.getAttribute("name")||""}:${e.getAttribute("property")||""}:${e.getAttribute("http-equiv")||""}:${e.hasAttribute("charset")?"charset":""}:${e.getAttribute("media")||""}`;if("link"===t)return`link:${e.getAttribute("rel")||""}:${e.getAttribute("href")||""}:${e.getAttribute("media")||""}:${e.getAttribute("hreflang")||""}`;if("base"===t)return"base";if("script"===t){const t=e.getAttribute("src")||"",n=e.getAttribute("id")||"",r=e.getAttribute("type")||"";return t||n?`script:${t}:${n}:${r}`:`script::${r}:${e.outerHTML.slice(0,100)}`}if("style"===t){const t=e.getAttribute("id")||"",n=e.getAttribute("media")||"";return t?`style:${t}:${n}`:`style::${n}:${e.outerHTML.slice(0,100)}`}return`${t}:${e.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const e=new Map;for(const t of Array.from(document.head.children)){const n=this._getKey(t);e.has(n)||e.set(n,t)}return e}_captureInitialHead(){const e=document.head;for(const t of Array.from(e.children)){const e=this._getKey(t);Gl.has(e)||Gl.set(e,t.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of Bl)for(const n of t._childElementArray)e.add(this._getKey(n));for(const t of Gl.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=Bl.length-1;t>=0;t--){const r=Bl[t];for(const t of r._childElementArray)if(this._getKey(t)===n){e=t.cloneNode(!0);break}if(e)break}!e&&Gl.has(n)&&(e=Gl.get(n).cloneNode(!0));const r=t.get(n)??null;e?(r?r.replaceWith(e):document.head.appendChild(e),t.set(n,e),Qo(e)||Cl(e,`<${e.tagName.toLowerCase()}> inside <${go.head}>`,`<${go.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(go.layout)||e.define(go.layout,Do),e.get(go.layoutOutlet)||e.define(go.layoutOutlet,il),e.get(go.outlet)||e.define(go.outlet,Uo),e.get(go.route)||e.define(go.route,Oo),e.get(go.router)||e.define(go.router,zl),e.get(go.link)||e.define(go.link,ql),e.get(go.head)||e.define(go.head,Jl)}(void 0);const Ql="data-fetchtarget",Xl={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let Yl=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 Zl(e,t){return t.every(t=>"available"===e.availability.get(t))}const ea=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]),ta=new Set(["GET","HEAD","OPTIONS"]);let na=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 Yl("fetch","latest",{withSignal:!0});_inFlight=null;_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 Zl(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}}(ea,{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(!Zl(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._inFlight;null===n||ta.has(n.method)||console.warn(`[@wcstack/fetch] [wcs/fetch-request-superseded] A ${n.method} request to "${n.url}" was still in flight when another request started on the same element: it was aborted and its response dropped (the server may have applied it). Give each change its own <wcs-fetch>, or wait for loading to end before starting the next request.`);const r=this._lane.begin(),{ticket:i,attempt:s}=r,o=s.signal,l={method:String(t.method??"GET").toUpperCase(),url:e};this._inFlight=l,this._commitStep(i,()=>this._setLoading(!0)),this._commitStep(i,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:a="GET",body:u=null,contentType:c=null,forceText:h=!1,responseType:d="auto",timeout:f=0}=t;let p=null;f>0&&(p=setTimeout(()=>{if(!this._lane.claimTerminal(i,"timeout"))return;const e=`Request timed out after ${f}ms.`;this._commitStep(i,()=>{this._setErrorInfo("timeout","execute",!0,e),this._setError({name:"TimeoutError",message:e})}),this._commitStep(i,()=>this._setResponse(null,0)),this._commitStep(i,()=>this._setLoading(!1)),this._lane.abort(i),this._lane.finalize(i)},f));const m={...t.headers??{}};try{c&&!m["Content-Type"]&&(m["Content-Type"]=c);const t={method:a,headers:m,signal:o};"GET"!==a&&"HEAD"!==a&&null!==u&&(t.body=u);const n=await globalThis.fetch(e,t);let r=null;if("HEAD"===a);else if(n.ok)if(h)r=await n.text();else if("blob"===d)r=await n.blob();else if("arrayBuffer"===d)r=await n.arrayBuffer();else if("text"===d)r=await n.text();else if("json"===d)r=await n.json();else{const e=n.headers.get("Content-Type")||"";r=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(i,"error")?(this._commitStep(i,()=>{this._setErrorInfo("http-error","execute",!0,`HTTP ${n.status} ${n.statusText}`),this._setError(t)}),this._commitStep(i,()=>this._setResponse(null,n.status)),this._commitStep(i,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(i,"success"))return null;const s=r instanceof Blob?this._createObjectURL(r):null;return this._commitStep(i,()=>this._setResponse(r,n.status,s)),this._commitStep(i,()=>this._setLoading(!1)),this._value}catch(e){return e&&"AbortError"===e.name?(this._lane.claimTerminal(i,"aborted")&&this._commitStep(i,()=>this._setLoading(!1)),null):this._lane.claimTerminal(i,"error")?(this._commitStep(i,()=>{const t=String(e?.message??"Network request failed.");this._setErrorInfo("network","execute",!0,t),this._setError(e??{message:t})}),this._commitStep(i,()=>this._setResponse(null,0)),this._commitStep(i,()=>this._setLoading(!1)),null):null}finally{this._inFlight===l&&(this._inFlight=null),null!==p&&clearTimeout(p),this._lane.finalize(i)}}},ra=!1;function ia(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest(`[${Ql}]`);if(!n)return;const r=n.getAttribute(Ql);if(!r)return;const i=customElements.get(Xl.fetch),s=document.getElementById(r);if(!(i&&s instanceof i))return;const o=s;o.url&&(e.preventDefault(),o.fetch())}function sa(e,t){let n=Object.getPrototypeOf(e);for(;null!==n;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return"function"==typeof e.get||"function"==typeof e.set;n=Object.getPrototypeOf(n)}return!1}const oa=new WeakMap;function la(e,t){let n=oa.get(e);return void 0===n&&(n=new Map,oa.set(e,n)),n.has(t)||n.set(t,e.getAttribute(t)),n.get(t)}function aa(e,t,n){null===n?e.removeAttribute(t):e.setAttribute(t,n)}function ua(e,t,n){const r=la(e,t);aa(e,t,void 0===n?r:null===n?null:String(n))}const ca=Symbol.for("wcstack.trustedTypes.policy");function ha(){const e=globalThis[ca];return null===e||"object"!=typeof e?null:e}let da,fa=!1;let pa=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static hasPendingPromise=!0;static wcBindable={...na.wcBindable,properties:[...na.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 na(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){ua(this,"url",e)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(e){ua(this,"method",e)}get target(){return this.getAttribute("target")}set target(e){ua(this,"target",e)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(e){ua(this,"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 pendingPromise(){return this._autoPending&&!this.manual&&this.url?Promise.resolve().then(()=>this.pendingPromise??void 0):this.loading?this._core.promise.then(()=>{}):null}get manual(){return this.hasAttribute("manual")}set manual(e){!function(e,t,n){const r=la(e,t);aa(e,t,void 0===n?r:n?"":null)}(this,"manual",e)}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(Xl.fetchHeader);for(const n of t)n.hasHeader&&(e[n.headerName]=n.headerValue);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(Xl.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;t||(this._lastFetchedUrl=null),this.isConnected&&!this.manual&&t&&t!==this._lastFetchedUrl?(null===e&&this._warnUnsafeAutoFetch(),this.fetch().finally(()=>e?.())):e?.()}))}_warnUnsafeAutoFetch(){const e=this.method;"GET"!==e&&"HEAD"!==e&&"OPTIONS"!==e&&null===this._body&&null===this.querySelector(Xl.fetchBody)&&console.warn(`[@wcstack/fetch] [wcs/fetch-auto-unsafe] The url changed to "${this.url}", so this <wcs-fetch> sent a ${e} with no body (its method stays ${e}; a body is sent once). Give loading and each change its own <wcs-fetch>, or set \`manual\` on the one that changes data.`)}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=ha(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(t)}catch(e){if(function(){if(void 0!==da)return da;if(!("trustedTypes"in globalThis))return da=!1,da;try{document.createElement("div").innerHTML="<i></i>",da=!1}catch{da=!0}return da}())return void function(){if(fa)return;fa=!0;const e="function"==typeof ha()?.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(!sa(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this.style.display="none",ra||(ra=!0,document.addEventListener("click",ia)),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(e=>{this._connectResolve=e})),this._scheduleAutoFetch()}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}};class ma extends HTMLElement{connectedCallback(){for(const e of["name","value"])if(Object.prototype.hasOwnProperty.call(this,e)){const t=this[e];delete this[e],this[e]=t}this.style.display="none"}get name(){return this.getAttribute("name")??""}set name(e){ua(this,"name",e)}get value(){return this.getAttribute("value")??""}set value(e){ua(this,"value",e)}get headerName(){return this.name}get headerValue(){return this.value}get hasHeader(){return""!==this.name&&this.hasAttribute("value")}}class ga extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}class ya extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;_warnedTarget=null;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 pa?e.loading||(e.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())):this._warnedTarget!==this.target&&(this._warnedTarget=this.target,console.warn(`[@wcstack/fetch] [wcs/infinite-scroll-target] <${Xl.infiniteScroll} target="${this.target}"> came into view, but no <${Xl.fetch}> has that id, so no page was loaded.`))}}!function(e=customElements){e.get(Xl.fetch)||e.define(Xl.fetch,pa),e.get(Xl.fetchHeader)||e.define(Xl.fetchHeader,ma),e.get(Xl.fetchBody)||e.define(Xl.fetchBody,ga),e.get(Xl.infiniteScroll)||e.define(Xl.infiniteScroll,ya)}(void 0);const ba="data-storagetarget",va={storage:"wcs-storage"},wa="wcs-storage:value-changed",_a="wcs-storage:loading-changed",$a="wcs-storage:error",ka="wcs-storage:error-info-changed",Sa="wcs-storage:trigger-changed";let Na=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:wa,semantics:"state",getter:e=>e.detail},{name:"loading",event:_a,semantics:"state"},{name:"error",event:$a,semantics:"state"},{name:"errorInfo",event:ka,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(_a,{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($a,{detail:e,bubbles:!0})))}_commitErrorInfo(e){this._errorInfo=e,this._target.dispatchEvent(new CustomEvent(ka,{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(wa,{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)}},Ea=!1;function Aa(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest(`[${ba}]`);if(!n)return;const r=n.getAttribute(ba);if(!r)return;const i=customElements.get(va.storage),s=document.getElementById(r);i&&s instanceof i&&(e.preventDefault(),s.save())}function Ca(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 xa=new WeakMap;function Ta(e,t){let n=xa.get(e);return void 0===n&&(n=new Map,xa.set(e,n)),n.has(t)||n.set(t,e.getAttribute(t)),n.get(t)}function Pa(e,t,n){null===n?e.removeAttribute(t):e.setAttribute(t,n)}function Oa(e,t,n){const r=Ta(e,t);Pa(e,t,void 0===n?r:null===n?null:String(n))}class Ma extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Na.wcBindable,properties:[...Na.wcBindable.properties,{name:"trigger",event:Sa,semantics:"state"}],inputs:[{name:"key"},{name:"type"},{name:"value"},{name:"manual"},{name:"trigger"}]};static get observedAttributes(){return["key","type"]}_core;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_internals=null;constructor(){super(),this._core=new Na(this),this._internals=this._initInternals(),this._wireStates({[_a]:e=>({loading:!0===e}),[$a]: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){Oa(this,"key",e)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(e){Oa(this,"type",e)}_warnedType=null;_checkType(){const e=this.getAttribute("type");null!==e&&""!==e&&"local"!==e&&"session"!==e&&e!==this._warnedType&&(this._warnedType=e,console.warn(`[@wcstack/storage] [wcs/storage-type-invalid] <${va.storage} type="${e}"> is neither "local" nor "session": it uses localStorage, so the data is kept after the session ends.`))}get value(){return this._core.value}set value(e){void 0!==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){!function(e,t,n){const r=Ta(e,t);Pa(e,t,void 0===n?r:n?"":null)}(this,"manual",e)}get trigger(){return this._trigger}set trigger(e){if(e){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(Sa,{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._checkType(),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(!Ca(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this.style.display="none",this._checkType(),Ea||(Ea=!0,document.addEventListener("click",Aa)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}}!function(e=customElements){e.get(va.storage)||e.define(va.storage,Ma)}(void 0);const La="*",Ia="vanilla",ja={loaders:{[Ia]:{postfix:".js",loader:async function(e){return(await(import(`${e}`))).default}},[La]:Ia},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function Ra(e){if(e.startsWith("@components/")){if(e.endsWith("/")){const t=e.slice(12,e.length-1),[n,r]=t.split("|",2);if(""===n)throw new Error("Invalid importmap key: "+e);return{key:e,prefix:n.replaceAll("/","-").toLowerCase(),loaderKey:r??null,isNameSpaced:!0}}{const t=e.slice(12),[n,r]=t.split("|",2),[i,s]=(r??"").split(",",2);if(""===n)throw new Error("Invalid importmap key: "+e);return{key:e,tagName:n.replaceAll("/","-").toLowerCase(),loaderKey:i||null,extends:s||null,isNameSpaced:!1}}}return null}function Ha(e,t,n){let r;if(null===t||t===La||""===t){let t=null;const i=[];for(const[e,t]of Object.entries(n)){if(e===La)continue;const r="string"==typeof t?n[t]:t;"string"!=typeof r&&i.push(r)}i.sort((e,t)=>t.postfix.length-e.postfix.length);for(const n of i)if(e.endsWith(n.postfix)){t=n;break}t?r=t:(r=n[La],"string"==typeof r&&(r=n[r]))}else if(r=n[t],!r)throw new Error("Loader not found: "+t);if("string"==typeof r)throw new Error("Loader redirection is not supported here");return r}const Wa=new Set,Da=new Map;let Ua=new WeakMap;function za(e){if(e===globalThis.customElements)return Da;let t=Ua.get(e);return void 0===t&&(t=new Map,Ua.set(e,t)),t}const Fa=new Map;async function qa(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 Fa)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){Wa.has(t)||(console.error(`Failed to eager load component '${t}':`,e),Wa.add(t))}}function Ba(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined||"function"!=typeof t.define?null:t}function Ga(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&&Fa.set(e,t)});const Ka=new WeakSet,Va=new WeakSet;async function Ja(e,t,n){e.shadowRoot&&(Ka.has(e)||await async function(e,t,n){Ka.add(e),await Za(e.shadowRoot,t,n)}(e,t,n))}async function Qa(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=za(r),o=s.get(e.name);if(void 0!==o)return void await o;const l=async function(e,t,n,r){try{let i;try{i=Ha("",n.loaderKey,t.loaders)}catch(t){throw new Error("Loader redirection is not supported for lazy loaded components: "+e.name)}const s=e.name.slice(n.prefix.length+1);if(""===s)throw new Error("Invalid component name for lazy loaded component: "+e.name);const o=n.key+s+i.postfix;if(r.get(e.name))return;const l=await i.loader(o);if(null===l)throw new Error("Loader returned null for component: "+e.name);if(r.get(e.name))return;null===e.extends?r.define(e.name,l):r.define(e.name,l,{extends:e.extends})}catch(t){console.error(`Failed to lazy load component '${e.name}':`,t),Wa.add(e.name)}}(e,t,i,r);s.set(e.name,l);try{await l}finally{s.delete(e.name)}}async function Xa(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=Ga(e);void 0===r.get(i.name)?(Va.has(e)||(Va.add(e),r.whenDefined(i.name).then(async()=>{await Ja(e,t,n)})),l.has(i.name)||Wa.has(i.name)||(l.add(i.name),o.push(i))):await Ja(e,t,n)}let a=0;for(const e of o)await Qa(e,t,n,r),a++;return a}async function Ya(e,t,n,r){for(;await Xa(e,t,n,r)>0;);}async function Za(e,t,n){if(0===Object.keys(n).length)return null;const r=function(e=null){if(null!=e){const t=e.customElementRegistry;if(null===t)return null;if(void 0!==t)return Ba(t)}return Ba(globalThis.customElements)}(e);if(null===r)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await Ya(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 Ya(e,t,n,r)}catch(e){console.error("Failed to lazy load components: "+e)}});return i.observe(e,{childList:!0,subtree:!0}),i}class eu extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),eu._instance)throw new Error(`${ja.tagNames.autoloader} can only be instantiated once.`);eu._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=Ra(r);null!==e&&(e.isNameSpaced?t[e.prefix]=e:n[e.tagName]=e)}return{prefixMap:t,loadMap:n}}(e);this._prefixMap=t,async function(e,t){const n=[];for(const[r,i]of Object.entries(e)){let s;try{s=Ha(i.key,i.loaderKey,t)}catch(e){throw new Error("Loader redirection is not supported for eager loaded components: "+r)}n.push(qa(i,r,s))}await Promise.all(n)}(n,ja.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 Za(document,ja,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,eu._instance===this&&(eu._instance=null)}}!function(e=customElements){e.get(ja.tagNames.autoloader)||e.define(ja.tagNames.autoloader,eu)}(void 0);
|
|
2
2
|
//# sourceMappingURL=auto.min.js.map
|