@wcstack/router 2.0.0 → 2.1.1

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.ja.md CHANGED
@@ -356,7 +356,7 @@ console.log(router.typedParams.userId); // 123 (number)
356
356
  a.active { font-weight: bold; color: blue; }
357
357
  ```
358
358
 
359
- **属性の転送**: `<a>` の生成時に、すべての `aria-*` 属性と固定 5 名(`title` / `rel` / `target` / `download` / `hreflang`)をホストから anchor へコピーする。`to` / `style` / `class` は決して転送しない(ホストは `display:none` であり、`class` は `active` 契約を持つ)。接続後に追従するのは固定 5 名のみで、**動的な `aria-*` 変更は anchor に届かない** — `<wcs-link data-wcs="attr.aria-label: ...">` のような `data-wcs` バインドもコピー後にホストへ書くため届かない。`<wcs-link>` の `aria-*` は静的属性で書くこと。
359
+ **属性の転送**: `<a>` の生成時に、すべての `aria-*` 属性と固定 7 名(`title` / `rel` / `target` / `download` / `hreflang` / `lang` / `dir`)をホストから anchor へコピーする(`lang` / `dir` はスクリーンリーダーの読み上げ言語・方向に直結する)。`to` / `style` / `class` は決して転送しない(ホストは `display:none` であり、`class` は `active` 契約を持つ)。接続後に追従するのは固定 7 名のみで、**動的な `aria-*` 変更は anchor に届かない** — `<wcs-link data-wcs="attr.aria-label: ...">` のような `data-wcs` バインドもコピー後にホストへ書くため届かない。`<wcs-link>` の `aria-*` は静的属性で書くこと。
360
360
 
361
361
  **素の `<a>` について**: Navigation API のあるブラウザでは、basename 配下の素の `<a href="/about">` も SPA 遷移になる(router が intercept する)。フォールバックブラウザでは成立しない(SPA 経路は `<wcs-link>` の click ハンドラのみ)ため、推奨は `<wcs-link>` のまま。
362
362
 
@@ -457,8 +457,8 @@ router は、プラットフォームが既に正しく行うことについて
457
457
 
458
458
  **オプトインのポリシー** — `<wcs-router focus="heading" announce="title">`。どちらも既定はオフで、属性が無ければ上記のブラウザ挙動がすべて。どちらも commit したナビゲーションの直後にだけ走り、最初のルート適用(ページロードはブラウザの担当)と guard 拒否されたナビゲーションでは決して動かない。
459
459
 
460
- - `focus="heading"`: **リーフ** route が挿入した内容の最初の `h1`〜`h6` へフォーカスを移す(見出しに tabindex が無ければ `tabindex="-1"` を付与)。指定中は Navigation API 経路で `focusReset: "manual"` を渡し、ブラウザ既定のリセットとの二重処理を防ぐ。新しい内容に見出しが無ければ何もしない — オプトインするなら各ルートに見出しを置くこと。
461
- - `announce="title"`: commit 時点の `document.title` のスナップショットを router 保有の live region(`role="status"`・視覚的にクリップ・`<wcs-router>` 直下・router ごとに 1 つ)へ書き込む。既知の制限: バインド title(`<title data-wcs>`)は commit 時点で古いことがあり、ナビゲーション外の title 変化は再読み上げされない。
460
+ - `focus="heading"`: **リーフ** route が挿入した内容の最初の**可視の** `h1`〜`h6` へフォーカスを移す(見出しに tabindex が無ければ `tabindex="-1"` を付与。`hidden` / `display:none` の見出しは focus() が空振りするためスキップ)。指定中は Navigation API 経路で `focusReset: "manual"` を渡し、ブラウザ既定のリセットとの二重処理を防ぐ。可視の見出しが無ければ、router が仕様既定のリセットを自前で再現する — 最初の `[autofocus]` 要素へ、無ければ `<body>` へ落とす(永続ナビのリンク等、旧フォーカス要素が遷移後も生き残るケースでフォーカスが前画面に取り残されないため)。それでもオプトインするなら各ルートに見出しを置き、ルート内容の**冒頭**に置くこと — 見出しへの focus はスクロールインを起こすが、push 遷移直後の scroll-to-top が勝つため、ページ下方の見出しは画面外のままフォーカスされる。ポリシーが有効になるのは値がちょうど `"heading"` のときだけで、空文字・未知値はブラウザ既定に落ちる。
461
+ - `announce="title"`: commit 時点の `document.title` のスナップショットを router 保有の live region(`role="status"`・視覚的にクリップ・`<wcs-router>` 直下・router ごとに 1 つ)へ書き込む。既知の制限: バインド title(`<title data-wcs>`)は commit 時点で古いことがあり、ナビゲーション外の title 変化は再読み上げされない。また同じ title を共有するルート間の遷移は live region のテキストが変化しないため、SR / ブラウザの組み合わせによっては再読み上げされないことがある。
462
462
 
463
463
  設計の記録は [docs/a11y-design.md](https://github.com/wcstack/wcstack/blob/main/docs/a11y-design.md) §3 を参照。
464
464
 
package/README.md CHANGED
@@ -356,7 +356,7 @@ Link. Converted to an `<a>`, and the route path in the `to` attribute is convert
356
356
  a.active { font-weight: bold; color: blue; }
357
357
  ```
358
358
 
359
- **Attribute forwarding**: when the `<a>` is generated, all `aria-*` attributes plus five fixed names (`title`, `rel`, `target`, `download`, `hreflang`) are copied from the host to the anchor. `to`, `style`, and `class` are never forwarded (the host is `display:none`, and `class` carries the `active` contract). After connection, only the five fixed names keep tracking changes; **dynamic `aria-*` changes do not reach the anchor** — this includes `data-wcs` bindings such as `<wcs-link data-wcs="attr.aria-label: ...">`, which write to the host after the copy has happened. Write `aria-*` on `<wcs-link>` as static attributes.
359
+ **Attribute forwarding**: when the `<a>` is generated, all `aria-*` attributes plus seven fixed names (`title`, `rel`, `target`, `download`, `hreflang`, `lang`, `dir`) are copied from the host to the anchor (`lang` / `dir` matter to screen readers — they set the announcement language and direction of the link text). `to`, `style`, and `class` are never forwarded (the host is `display:none`, and `class` carries the `active` contract). After connection, only the seven fixed names keep tracking changes; **dynamic `aria-*` changes do not reach the anchor** — this includes `data-wcs` bindings such as `<wcs-link data-wcs="attr.aria-label: ...">`, which write to the host after the copy has happened. Write `aria-*` on `<wcs-link>` as static attributes.
360
360
 
361
361
  **Plain `<a>` note**: in browsers with the Navigation API, a plain `<a href="/about">` under the basename also becomes an SPA navigation (the router intercepts it). This does not hold in fallback browsers, where only `<wcs-link>`'s click handler provides SPA navigation — so `<wcs-link>` remains the recommendation.
362
362
 
@@ -457,8 +457,8 @@ These are the specification defaults; writing them out records the delegation as
457
457
 
458
458
  **Opt-in policies** — `<wcs-router focus="heading" announce="title">`. Both default to off; with no attribute, the browser behavior above is all there is. Both run right after a committed navigation, never on the first route application (page load belongs to the browser), and never on a guard-rejected navigation.
459
459
 
460
- - `focus="heading"`: moves focus to the first `h1`–`h6` of the **leaf** route's inserted content, adding `tabindex="-1"` when the heading has none. While set, the router passes `focusReset: "manual"` on the Navigation API path so the browser's reset does not double-handle. If the new content has no heading, nothing happens — give every route a heading when you opt in.
461
- - `announce="title"`: writes the commit-time `document.title` snapshot into a router-owned live region (`role="status"`, visually clipped, direct child of `<wcs-router>`, one per router). Known limits: a bound title (`<title data-wcs>`) may still be stale at commit, and a title change outside navigation is not re-announced.
460
+ - `focus="heading"`: moves focus to the first **visible** `h1`–`h6` of the **leaf** route's inserted content, adding `tabindex="-1"` when the heading has none (hidden headings — `hidden`, `display:none` — are skipped, since focusing them is a no-op). While set, the router passes `focusReset: "manual"` on the Navigation API path so the browser's reset does not double-handle. If the new content has no visible heading, the router reproduces the spec-default reset itself: focus moves to the first `[autofocus]` element, or to `<body>` when there is none — the previously focused element (say, a persistent nav link) would otherwise keep focus on the old screen. Still: give every route a heading when you opt in, and put it near the top of the route content — focusing a heading scrolls it into view, but the scroll-to-top that follows a push navigation wins, so a heading far down the page ends up focused off-screen. Only the exact value `"heading"` activates the policy; an empty or unknown value falls back to the browser default.
461
+ - `announce="title"`: writes the commit-time `document.title` snapshot into a router-owned live region (`role="status"`, visually clipped, direct child of `<wcs-router>`, one per router). Known limits: a bound title (`<title data-wcs>`) may still be stale at commit, a title change outside navigation is not re-announced, and navigating between routes that share the same title may not be re-announced by some screen reader / browser combinations (the live region text does not change).
462
462
 
463
463
  See [docs/a11y-design.md](https://github.com/wcstack/wcstack/blob/main/docs/a11y-design.md) §3 for the design record.
464
464
 
package/dist/auto.min.js CHANGED
@@ -1,2 +1,2 @@
1
- const t={tagNames:{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"},enableShadowRoot:!1,basenameFileExtensions:[".html"]};function e(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function a(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}class n extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}}const s={int:{typeName:"int",pattern:/^-?\d+$/,parse(t){if(this.pattern.test(t))return parseInt(t,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(t){if(this.pattern.test(t))return parseFloat(t)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(t){if(this.pattern.test(t))return"true"===t||"1"===t}},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(t){if(this.pattern.test(t))return t}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(t){if(this.pattern.test(t))return t}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(t){if(!this.pattern.test(t))return;const[e,a,n]=t.split("-").map(Number),s=new Date(e,a-1,n);return s.getFullYear()===e&&s.getMonth()===a-1&&s.getDate()===n?s:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(t){if(this.pattern.test(t))return t}}},i={static:2,param:1,"catch-all":0};class r 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(t){super(),this._target=t??this}get parentCore(){return this._parentCore}set parentCore(t){this._parentCore=t}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,n){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&a(`${t.tagNames.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&a(`${t.tagNames.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?e(this._parentCore):n()}get absolutePath(){return this._checkParentCore(t=>{const e=t.absolutePath;return e.endsWith("/")?e+this._path:e+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(t=>[...t.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 t=[];for(const e of this._segmentInfos)e.paramName&&t.push(e.paramName);this._paramNames=t}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(t=>[...t.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let t=0;for(const e of this._segmentInfos)t+=i[e.type];this._weight=t}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(t=>t.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let t=0;for(const e of this._segmentInfos)"catch-all"!==e.type&&t++;this._segmentCount=""===this._path?0:t}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(t=>t.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(t,e={}){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=t,this._name=e.name||"",this._isFallbackRoute=e.isFallback||!1,e.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const a=t.split("/");for(let t=0;t<a.length;t++){const n=a[t];if(!(""===n&&t===a.length-1&&t>0)){if("*"===n){this._segmentInfos.push({type:"catch-all",segmentText:n,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(n.startsWith(":")){const t=n.match(/^:([^()]+)(\(([^)]+)\))?$/);let e,a="any";t?(e=t[1],t[3]&&Object.keys(s).includes(t[3])&&(a=t[3])):e=n.substring(1),this._segmentInfos.push({type:"param",segmentText:n,paramName:e,pattern:new RegExp("^([^\\/]+)$"),paramType:a})}else""===n&&e.isIndex||this._segmentInfos.push({type:"static",segmentText:n,paramName:null,pattern:new RegExp(`^${n}$`)})}}this._hasGuard=e.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",this._waitForSetGuardHandler=new Promise(t=>{this._resolveSetGuardHandler=t}))}setParams(t,e){const a=this._active;this._params=t,this._typedParams=e,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:t,typedParams:e},bubbles:!0})),a||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const t=this._active;this._params={},this._typedParams={},this._active=!1,t&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(t){for(const e of this.paramNames)if(this._params[e]!==t[e])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||a(`${t.tagNames.route} has no guardHandler.`),this._guardHandler}set guardHandler(t){this._guardHandler=t,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(t){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const e=t.path,a=t.lastPath;if(!await this._guardHandler(e,a))throw new n("Navigation cancelled by guard.",this._guardFallbackPath)}else if(this._hasGuard&&this._guardHandlerLoadFailed)throw new n("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath)}}class o extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=e();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new r(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||a(`${t.tagNames.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t){for(this._childNodeArray=[...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(t){this._core.guardHandler=t}setParams(t,e){this._core.setParams(t,e)}clearParams(){this._core.clearParams()}shouldChange(t){return this._core.shouldChange(t)}async guardCheck(t){return this._core.guardCheck(t)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(e,n){if(this._initialized)return;let s;this._initialized=!0;let i=!1,r=!1;this.hasAttribute("path")?s=this.getAttribute("path")||"":this.hasAttribute("index")?(s="",i=!0):this.hasAttribute("fallback")?(s="",r=!0):a(`${t.tagNames.route} should have a "path" or "index" attribute.`),this._routerNode=e,this._routeParentNode=n;const o=n||e;o.routeChildNodes.push(this),this._childIndex=o.routeChildNodes.length-1,r&&(n&&a(`${t.tagNames.route} with fallback attribute must be a direct child of ${t.tagNames.router}.`),e.fallbackRoute&&a(`${t.tagNames.router} can have only one fallback route.`),e.fallbackRoute=this),n&&(this._core.parentCore=n._core),this._core.parsePath(s,{isIndex:i,isFallback:r,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}}const l=new Map;class h extends HTMLElement{_uuid=e();constructor(){super()}async _loadTemplateFromSource(e){try{const n=await fetch(e);n.ok||a(`${t.tagNames.layout} failed to fetch layout from source: ${e}, status: ${n.status}`);const s=await n.text();return l.set(e,s),s}catch(n){a(`${t.tagNames.layout} failed to load layout from source: ${e}, error: ${n}`,{cause:n})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const e=this.getAttribute("src"),a=this.getAttribute("layout");e&&a&&console.warn(`${t.tagNames.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(e)l.has(e)?n.innerHTML=l.get(e)||"":n.innerHTML=await this._loadTemplateFromSource(e)||"";else if(a){const e=this._loadTemplateFromDocument(a);e?n.innerHTML=e:console.warn(`${t.tagNames.layout} could not find template with id "${a}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&t.enableShadowRoot}get name(){return this.getAttribute("name")||""}}class c extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||a(`${t.tagNames.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&t.enableShadowRoot}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const u=new Set(["props","states","attr",""]);function d(t,e,a){for(const[n,s]of Object.entries(e))switch(a){case"props":t.props={...t.props,[n]:s};break;case"states":t.states={...t.states,[n]:s};break;case"attr":null==s?t.removeAttribute(n):t.setAttribute(n,String(s));break;case"":t[n]=s}}function m(t,e){t.hasAttribute("data-bind")||a(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";u.has(n)||a(`${t.tagName} has invalid 'data-bind' attribute: ${n}`);const s=n,i=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const a=t.getAttribute("is");return a&&a.includes("-")?a:null}(t);i&&void 0===customElements.get(i)?customElements.whenDefined(i).then(()=>{t.isConnected&&d(t,e,s)}).catch(()=>{a(`Failed to define custom element: ${i}`)}):d(t,e,s)}class p extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||a(`${t.tagNames.layoutOutlet} has no layout.`),this._layout}set layout(t){this._layout=t,this.setAttribute("name",t.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 t of Array.from(this.layout.childNodes))this._layoutChildNodes.push(t),this.appendChild(t)}else{const a=e.content.cloneNode(!0),n=new Map;a.querySelectorAll("slot").forEach(e=>{const a=e.getAttribute("name")||"";n.has(a)?console.warn(`${t.tagNames.layoutOutlet} duplicate slot name "${a}" in layout template.`):n.set(a,e)});const s=new Map,i=document.createDocumentFragment();for(const t of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(t),t instanceof Element){const e=t.getAttribute("slot")||"";if(e.length>0&&n.has(e)){s.has(e)||s.set(e,document.createDocumentFragment()),s.get(e)?.appendChild(t);continue}}i.appendChild(t)}for(const[t,e]of n){const a=s.get(t);a&&e.replaceWith(a)}const r=n.get("");r&&r.replaceWith(i),this.appendChild(a)}}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(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{m(e,t)}),e.hasAttribute("data-bind")&&m(e,t))}}function g(){return document.createElement(t.tagNames.layoutOutlet)}const _="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";async function f(t,e){let n=null,s=null;const i=e.uuid||"",r=`\n//# sourceURL=${i?`wcs-guard-handler:${i}`:"wcs-guard-handler"}\n`,o=t.text+r;let l=!1;const h=t=>{t.effectiveDirective.startsWith("script-src")&&(l=!0)};document.addEventListener("securitypolicyviolation",h);try{if("function"==typeof URL.createObjectURL){const t=new Blob([o],{type:"application/javascript"}),e=URL.createObjectURL(t);try{n=await import(e)}catch(t){s=t}finally{URL.revokeObjectURL(e)}}if(!n){const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(o)));try{n=await import(`data:application/javascript;base64,${t}`)}catch(t){a(function(t,e,a){return a?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL, so script-src must allow blob:. See ${_}`:`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"")+`. If this page sets a Content-Security-Policy, see ${_}`}(t,s,l),{cause:s??t})}}}finally{document.removeEventListener("securitypolicyviolation",h)}return n&&"function"==typeof n.default?n.default:null}function b(t,e){f(t,e).then(t=>{t?e.guardHandler=t:e.notifyGuardHandlerLoadFailed()}).catch(t=>{console.error("loadGuardHandler failed:",t),e.notifyGuardHandlerLoadFailed()})}function y(t,e){let a=t.get(e.absolutePath);a||(a=[]);for(const t of a)if(!e.testAncestorNode(t)){console.warn(`Duplicate route path detected: '${e.absolutePath}' (defined as '${e.path}')`);break}a.push(e),1===a.length&&t.set(e.absolutePath,a)}async function w(e,a,n,s){const i=n.length>0?n[n.length-1]:null,r=document.createDocumentFragment(),o=Array.from(a.childNodes);for(const a of o)if(a.nodeType===Node.ELEMENT_NODE){let o=a,l=a;const h=l.tagName.toLowerCase();if(h===t.tagNames.route){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const a=document.importNode(l,!0);customElements.upgrade(a),a.appendChild(t);const r=a;r.initialize(e,i),y(s,r),n.push(r),o=r.placeHolder,l=r}else{if(h===t.tagNames.guardHandler){if(n.length>0){const t=n[n.length-1],e=l.querySelector('script[type="module"]');e&&b(e,t)}continue}if("template"===h){r.appendChild(l);continue}if(h===t.tagNames.layout){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const e=document.importNode(l,!0);customElements.upgrade(e),e.appendChild(t);const a=e,n=g();n.layout=a,o=n,l=e}}const c=await w(e,l,n,s);l.innerHTML="",l.appendChild(c),r.appendChild(o)}else r.appendChild(a);return r}async function N(t){const e=new Map;return await w(t,t.template.content,[],e)}function v(t,e){if("title"===t.announcePolicy){const e=t.a11yRegion;null!==e&&(e.textContent=document.title)}if("heading"===t.focusPolicy){const t=function(t){for(const e of t){if(e.nodeType!==Node.ELEMENT_NODE)continue;const t=e;if(/^H[1-6]$/.test(t.tagName))return t;const a=t.querySelector("h1,h2,h3,h4,h5,h6");if(null!==a)return a}return null}(e.routes[e.routes.length-1].childNodeArray);null!==t&&(t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1"),t.focus())}}function C(t,e,a,n){const i=function(t,e,a){const n={},i={};let r=!0,o=!1,l=0,h=0;for(;l<t.absoluteSegmentInfos.length;){const e=t.absoluteSegmentInfos[l];if(e.isIndex){l++;continue}if(0===l&&""===e.segmentText&&"static"===e.type){l++;continue}const c=a[h];if(void 0===c){r=!1;break}let u=!1;if("param"===e.type){const t=e.paramType||"any",a=s[t].parse(c);void 0!==a&&(e.paramName&&(n[e.paramName]=c,i[e.paramName]=a),u=!0)}else u=null!==e.pattern.exec(c);if(!u){r=!1;break}if("catch-all"===e.type){const t=a.slice(h).join("/");n["*"]=t,i["*"]=t,o=!0;break}l++,h++}let c=!1;return r&&(o||l===t.absoluteSegmentInfos.length&&h===a.length)&&(c=!0),c?{path:e,routes:t.routes,params:n,typedParams:i,lastPath:""}:null}(t,e,a);i&&n.push(i);for(const s of t.routeChildNodes)C(s,e,a,n)}function P(t,e){const a=t.routeChildNodes,n=[],s=e.split("/"),i=s.filter((t,e)=>(0!==e||""!==t)&&!(e===s.length-1&&""===t&&s.length>1));for(const t of a)C(t,e,i,n);return n.sort((t,e)=>{const a=t.routes.at(-1),n=e.routes.at(-1),s=a.absoluteSegmentCount-n.absoluteSegmentCount;if(0!==s)return-s;const i=a.absoluteWeight-n.absoluteWeight;if(0!==i)return-i;return a.childIndex-n.childIndex}),n.length>0?n[0]:null}let E=null,A=null;function k(){const e=t.basenameFileExtensions;return 0===e.length?null:(E===e&&A||(E=e,A=new RegExp(`\\/[^/]+(?:${e.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),A)}function S(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const a=k();return a&&(e=e.replace(a,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function $(t,e){let a=t;return""!==e&&(t===e?a="":t.startsWith(e+"/")&&(a=t.slice(e.length))),""===a?"/":a}function x(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const a=k();return a&&(e=e.replace(a,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function R(t){t.clearParams();for(const e of t.childNodeArray)e.parentNode?.removeChild(e)}function L(e,a){const n={},s={};for(const t of e.paramNames)n[t]=a.params[t],s[t]=a.typedParams[t];e.setParams(n,s);for(const a of e.childNodeArray)if(a.nodeType===Node.ELEMENT_NODE){const n=a;n.querySelectorAll("[data-bind]").forEach(t=>{m(t,e.typedParams)}),n.hasAttribute("data-bind")&&m(n,e.typedParams),n.querySelectorAll(t.tagNames.layoutOutlet).forEach(t=>{t.assignParams(e.typedParams)}),n.tagName.toLowerCase()===t.tagNames.layoutOutlet&&n.assignParams(e.typedParams)}}function H(t,e){L(t,e);const a=t.placeHolder.parentNode,n=t.placeHolder.nextSibling;for(const e of t.childNodeArray)n?a?.insertBefore(e,n):a?.appendChild(e);return!0}const z=Symbol.for("wcstack.transition-runner");function I(t,e,a){const n=function(t){const e=globalThis[z];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}(t);if(null!==n)return n.run(e,{source:t,types:a});e()}const T=Symbol.for("wcstack.binder");function F(){const t=globalThis[T];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const O=Symbol.for("wcstack.binder.pending"),M=Symbol.for("wcstack.binder.taken");function U(){const t=globalThis;let e=t[M];return void 0===e&&(e=new WeakSet,t[M]=e),e}function W(t){const e=F();return null===e?(function(){const t=globalThis;let e=t[O];return void 0===e&&(e=[],t[O]=e),e}().push(t),!1):(U().add(t),e.bind(t),!0)}const D=new WeakSet,j="data-wcs";function G(t,e,a){!D.has(t)&&function(t){return t.hasAttribute(j)||null!==t.querySelector(`[${j}]`)}(t)&&(D.add(t),function(t){if("complete"!==document.readyState)return void window.addEventListener("load",t,{once:!0});t()}(()=>{var n;null!==F()||(n=t,U().has(n))||console.warn(`[@wcstack/router] ${e} contains ${j} 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. ${a}`)}))}function B(t){for(const e of t.childNodeArray)1===e.nodeType&&(W(e)||G(e,`<${e.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 q(t,e){try{for(const t of e.routes)await t.guardCheck(e)}catch(e){if(e instanceof n)return console.warn(`Navigation cancelled: ${e.message}. Redirecting to ${e.fallbackPath}`),queueMicrotask(()=>{t.navigate(e.fallbackPath).catch(t=>{console.error("Fallback navigation failed:",t)})}),!1;throw e}return!0}async function K(e,n,s,i,r=""){const o=$(s,e.basename);if(e.isSameMatch(o))return e.commitNavigation({params:e.params,typedParams:e.typedParams,routeName:e.routeName,search:r,path:o}),!0;let l=P(e,o);l||(e.fallbackRoute?l={routes:[e.fallbackRoute],params:{},typedParams:{},path:o,lastPath:i}:a(`${t.tagNames.router} No route matched for path: ${o}`)),l.lastPath=i;const h=n.lastRoutes,c=await async function(t,e,a){if(!await q(t,e))return!1;const n=new Set(e.routes),s=new Set(a),i=()=>{for(const t of a)n.has(t)||R(t);let t=!1;for(const n of e.routes)(!s.has(n)||n.shouldChange(e.params)||t)&&(t=H(n,e),a.length>0&&!s.has(n)&&B(n))};let r;return 0===a.length?i():r=I("router",i),void 0!==r&&await r,!0}(e,l,h);return!!c&&(e.commitNavigation({params:l.params,typedParams:l.typedParams,routeName:l.routes[l.routes.length-1]?.name??"",search:r,path:o}),n.lastRoutes=l.routes,h.length>0&&v(e,l),!0)}function Y(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function J(t,e){const a=Object.keys(t),n=Object.keys(e);if(a.length!==n.length)return!1;for(const n of a){if(!Object.prototype.hasOwnProperty.call(e,n))return!1;if(t[n]!==e[n])return!1}return!0}function Q(t){let e=t,a="";const n=e.indexOf("#");n>=0&&(a=e.slice(n),e=e.slice(0,n));let s="";const i=e.indexOf("?");return i>=0&&(s=e.slice(i),e=e.slice(0,i)),{pathname:e,search:s,hash:a}}function V(t){return"?"===t?"":t}function X(t,e){let a=Object.getPrototypeOf(t);for(;null!==a;){const t=Object.getOwnPropertyDescriptor(a,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;a=Object.getPrototypeOf(a)}return!1}function Z(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const tt="data-wcs-ssr",et="data-wcs-ssr-link",at="@@wcs-route-ph:",nt="@@wcs-route-start:",st="@@wcs-route-end:",it=Object.freeze({});class rt 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:t=>t.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=it;_typedParams=it;_searchParams=it;_routeName="";_hasCommitted=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._connectedCallbackPromise.catch(()=>{})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get a11yRegion(){return this._a11yRegion}get focusPolicy(){return this.getAttribute("focus")}get announcePolicy(){return this.getAttribute("announce")}_ensureA11yRegion(){if(null!==this._a11yRegion)return;const t=document.createElement("div");t.setAttribute("role","status"),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.clipPath="inset(50%)",t.style.whiteSpace="nowrap",this.appendChild(t),this._a11yRegion=t}_normalizePathname(t){return S(t)}_normalizeBasename(t){return x(t)}_joinInternalPath(t,e){const a=this._normalizeBasename(t);let n=e.startsWith("/")?e:"/"+e;return n=this._normalizePathname(n),a?"/"===n?a+"/":a+n:n}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let t=new URL(document.baseURI).pathname||"/";return"/"===t?"":this._normalizeBasename(t)}get basename(){return this._basename}_getOutlet(){const e=this.nextElementSibling;if(e&&e.matches(t.tagNames.outlet))return e;const a=document.createElement(t.tagNames.outlet);return this.parentNode?this.parentNode.insertBefore(a,this.nextSibling):document.body.appendChild(a),a}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||a(`${t.tagNames.router} has no outlet.`),this._outlet}get template(){return this._template||a(`${t.tagNames.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(t){const e=this._path!==t;this._path=t,e&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t){const e=Object.freeze({...t.params}),a=Object.freeze({...t.typedParams}),n=function(t){const e={};for(const[a,n]of new URLSearchParams(t))e[a]=n;return Object.freeze(e)}(t.search),s=!J(this._params,e),i=this._routeName!==t.routeName,r=!J(this._searchParams,n),o=this._path!==t.path;s&&(this._params=e,this._typedParams=a),i&&(this._routeName=t.routeName),r&&(this._searchParams=n),this._path=t.path,this._hasCommitted=!0,s&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),i&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),r&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),o&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t.path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(t){this._fallbackRoute=t}get navigateUrl(){return this._navigateUrl}set navigateUrl(e){null!=e&&""!==e&&this._navigateUrl!==e&&(this._navigateUrl=e,this.navigate(e).catch(e=>{console.error(`${t.tagNames.router} navigate failed:`,e)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(e){null!=e&&""!==e&&this._replaceUrl!==e&&(this._replaceUrl=e,this.replace(e).catch(e=>{console.error(`${t.tagNames.router} replace failed:`,e)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(t){await this._performNavigation(t,!1)}async replace(t){await this._performNavigation(t,!0)}async _performNavigation(t,e){const a=Q(t),n=""!==a.pathname||""===a.search&&""===a.hash?this._joinInternalPath(this._basename,a.pathname):window.location.pathname,s=n+V(a.search)+a.hash,i=Y();if(i?.navigate){const t=e?i.navigate(s,{history:"replace"}):i.navigate(s);await(t?.finished)}else{e?history.replaceState(null,"",s):history.pushState(null,"",s);const t=this._normalizePathname(n),i=this.isSameMatch($(t,this._basename));await K(this,this.outlet,t,this._path,V(a.search))&&!i&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||(t===this._basename||t.startsWith(this._basename+"/"))}_onNavigateFunc(e){if(!e.canIntercept||e.hashChange||null!==e.downloadRequest)return;const a=new URL(e.destination.url),n=this._normalizePathname(a.pathname);if(!this._isOwnPath(n))return;const s=this.isSameMatch($(n,this._basename)),i=s&&("push"===e.navigationType||"replace"===e.navigationType),r=a.search,o=this;e.intercept({handler:async()=>{try{await K(o,o.outlet,n,o.path,r)}catch(e){throw console.error(`${t.tagNames.router} applyRoute failed:`,e),e}},scroll:i?"manual":"after-transition",focusReset:s||null!==o.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await K(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const e=Z();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const n=null!==document.querySelector("base[href]"),s=new URL(window.location.href);""!==this._basename||n||"/"===s.pathname||a(`${t.tagNames.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||a(`${t.tagNames.router} should have a <template> child element.`);const i=e?this._template.content.cloneNode(!0):null,r=await N(this),o=!e&&this._outlet.hasAttribute(tt);if(o||this._outlet.rootNode.appendChild(r),null!==i){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(i)}0===this.routeChildNodes.length&&a(`${t.tagNames.router} has no route definitions.`),e||this._ensureA11yRegion();const l=this._normalizePathname(window.location.pathname);if(e)return await this._renderForSsr(l),void(this._initialized=!0);if(o){if(await this._hydrateFromSsr(l))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(tt);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(r)}await K(this,this.outlet,l,this._path,window.location.search||""),(o||null!==F())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(e){const a=this.outlet.rootNode,n=new Map;let s=!1;if(this._forEachRoute(t=>{n.has(t.absolutePath)?s=!0:n.set(t.absolutePath,t)}),s)return!1;if(null!==a.querySelector(t.tagNames.layoutOutlet))return!1;const i=new Map,r=new Map,o=new Map,l=document.createTreeWalker(a,NodeFilter.SHOW_COMMENT);let h=0;for(;l.nextNode();){const t=l.currentNode,e=t.data;if(h++,e.startsWith(at)){const a=e.slice(15);if(i.has(a)||!n.has(a))return!1;i.set(a,t)}else if(e.startsWith(nt)){const a=e.slice(18);if(r.has(a)||!n.has(a))return!1;r.set(a,{comment:t,index:h})}else if(e.startsWith(st)){const a=e.slice(16);if(o.has(a)||!n.has(a))return!1;o.set(a,{comment:t,index:h})}}if(r.size!==o.size)return!1;const c=[];for(const[t,e]of r){const a=o.get(t);if(!a)return!1;if(a.comment.parentNode!==e.comment.parentNode)return!1;if(a.index<=e.index)return!1;c.push({start:e.index,end:a.index})}for(const t of c)for(const e of c)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const u=$(e,this._basename);let d=P(this,u);if(!d){if(null===this._fallbackRoute)return!1;d={routes:[this._fallbackRoute],params:{},typedParams:{},path:u,lastPath:this._path}}if(d.lastPath=this._path,d.routes.length!==r.size)return!1;for(const t of d.routes)if(!r.has(t.absolutePath))return!1;const m=new Set;for(const t of this.routeChildNodes)m.add(t.absolutePath);for(const t of d.routes)for(const e of t.routeChildNodes)m.add(e.absolutePath);if(i.size!==m.size)return!1;for(const t of m)if(!i.has(t))return!1;for(const[t,e]of i){const a=n.get(t);e.parentNode.replaceChild(a.placeHolder,e)}for(const e of d.routes){const a=r.get(e.absolutePath).comment,n=o.get(e.absolutePath).comment,s=[],i=new Set;let l=a.nextSibling;for(;null!==l&&l!==n;){if(l.nodeType===Node.COMMENT_NODE){const t=l.data;if(t.startsWith(nt)){const e=t.slice(18);l=o.get(e).comment.nextSibling;continue}}if(i.has(l))l=l.nextSibling;else{if(l.nodeType===Node.ELEMENT_NODE&&l.tagName.toLowerCase()===t.tagNames.link){const t=l.anchorElement;null!==t&&i.add(t)}s.push(l),l=l.nextSibling}}e.adoptChildNodes(s)}for(const{comment:t}of r.values())t.remove();for(const{comment:t}of o.values())t.remove();this.outlet.removeAttribute(tt);for(const t of d.routes)L(t,d);return this.outlet.lastRoutes=d.routes,!await q(this,d)||(this.commitNavigation({params:d.params,typedParams:d.typedParams,routeName:d.routes[d.routes.length-1].name,search:window.location.search||"",path:u}),!0)}async _renderForSsr(e){const n=$(e,this._basename),s=P(this,n),i=s?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===i.length&&a(`${t.tagNames.router} No route matched for path: ${n}`),!i.some(t=>t.hasGuard)){await K(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${at}${t.absolutePath}`}),this.outlet.setAttribute(tt,"");for(const t of this.outlet.lastRoutes){const e=t.placeHolder.parentNode,a=t.childNodeArray,n=document.createComment(`${nt}${t.absolutePath}`),s=document.createComment(`${st}${t.absolutePath}`);e.insertBefore(n,a[0]??t.placeHolder.nextSibling);const i=a[a.length-1];e.insertBefore(s,i?i.nextSibling:n.nextSibling)}}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&W(e)}_forEachRoute(t,e=this){for(const a of e.routeChildNodes)t(a),this._forEachRoute(t,a)}async connectedCallback(){if(function(t){const e=t.constructor?.wcBindable,a=e?.inputs;if(void 0!==a)for(const e of a){const a=e.name;if(!Object.prototype.hasOwnProperty.call(t,a))continue;if(!X(t,a))continue;const n=t,s=n[a];delete n[a],n[a]=s}}(this),Z()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const t=Y();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(Y()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const ot=["title","rel","target","download","hreflang"];class lt extends HTMLElement{static get observedAttributes(){return["to",...ot]}_childNodeArray=[];_uuid=e();_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(t.tagNames.router);if(e)return this._router=e;const n=this.getRootNode(),s=n.querySelector?.(t.tagNames.router);if(s)return this._router=s;a(`${t.tagNames.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(t){return S(t)}_joinInternalPath(t,e){const a=x(t),n=e.startsWith("/")?e:"/"+e,s=this._normalizePathname(n);return a?"/"===s?a+"/":a+s:s}_isInternalTarget(t){return t.startsWith("/")||t.startsWith("?")}_setAnchorHref(e,n){if(this._isInternalTarget(n)){const{pathname:t,search:a,hash:s}=Q(n),i=""===t?window.location.pathname:this._joinInternalPath(this.router.basename,t);e.href=i+V(a)+s}else try{e.href=new URL(n).toString()}catch{a(`[${t.tagNames.link}] Invalid URL in 'to' attribute: ${n}`)}}connectedCallback(){Z()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(et)?t:null}_connect(){this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let a;if(null!==e)a=e,a.removeAttribute(et),this._childNodeArray=Array.from(a.childNodes),this._setAnchorHref(a,this._path);else{const e=this.nextSibling;a=document.createElement("a"),this._setAnchorHref(a,this._path);for(const t of Array.from(this.attributes))(t.name.startsWith("aria-")||ot.includes(t.name))&&a.setAttribute(t.name,t.value);for(const t of this._childNodeArray)a.appendChild(t);e?t.insertBefore(a,e):t.appendChild(a)}if(this._anchorElement=a,Z())return this._updateActiveState(),void a.setAttribute(et,"");Y()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!Y()?.navigate&&(this._onClick=async t=>{t.defaultPrevented||0===t.button&&(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||this._isInternalTarget(this._path)&&(t.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},a.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){Y()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const t=this._anchorElement;t&&(this._onClick&&(t.removeEventListener("click",this._onClick),this._onClick=void 0),t.remove(),this._anchorElement=null);for(const e of this._childNodeArray)t&&e.parentNode===t&&t.removeChild(e);this._router=null}attributeChangedCallback(t,e,a){if("to"===t&&e!==a)this._path=a||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(ot.includes(t)){const e=this._anchorElement;e&&(null===a?e.removeAttribute(t):e.setAttribute(t,a))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const t=this._normalizePathname(new URL(window.location.href).pathname),{pathname:e}=Q(this._path),a=this._normalizePathname(this._isInternalTarget(this._path)?""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e):e);this._anchorElement&&(t===a?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current","page")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const ht=[],ct=new Map;let ut=!1;const dt=new WeakMap;class mt 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 t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),ut||(this._captureInitialHead(),ut=!0),ht.push(this),this._reapplyHead()}disconnectedCallback(){const t=ht.indexOf(this);-1!==t&&ht.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||a("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=dt.get(t);if(void 0!==e)return e;const a=this._computeKey(t);return dt.set(t,a),a}_computeKey(t){const e=t.tagName.toLowerCase();if("title"===e)return"title";if("meta"===e){return`meta:${t.getAttribute("name")||""}:${t.getAttribute("property")||""}:${t.getAttribute("http-equiv")||""}:${t.hasAttribute("charset")?"charset":""}:${t.getAttribute("media")||""}`}if("link"===e){return`link:${t.getAttribute("rel")||""}:${t.getAttribute("href")||""}:${t.getAttribute("media")||""}:${t.getAttribute("hreflang")||""}`}if("base"===e)return"base";if("script"===e){const e=t.getAttribute("src")||"",a=t.getAttribute("id")||"",n=t.getAttribute("type")||"";return e||a?`script:${e}:${a}:${n}`:`script::${n}:${t.outerHTML.slice(0,100)}`}if("style"===e){const e=t.getAttribute("id")||"",a=t.getAttribute("media")||"";return e?`style:${e}:${a}`:`style::${a}:${t.outerHTML.slice(0,100)}`}return`${e}:${t.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const t=new Map;for(const e of Array.from(document.head.children)){const a=this._getKey(e);t.has(a)||t.set(a,e)}return t}_captureInitialHead(){const t=document.head;for(const e of Array.from(t.children)){const t=this._getKey(e);ct.has(t)||ct.set(t,e.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of ht)for(const a of t._childElementArray)e.add(this._getKey(a));for(const t of ct.keys())e.add(t);const a=this._buildHeadElementMap();for(const t of a.keys())e.add(t);for(const n of e){let e=null;for(let t=ht.length-1;t>=0;t--){const a=ht[t];for(const t of a._childElementArray)if(this._getKey(t)===n){e=t.cloneNode(!0);break}if(e)break}if(!e&&ct.has(n)){e=ct.get(n).cloneNode(!0)}const s=a.get(n)??null;e?(s?s.replaceWith(e):document.head.appendChild(e),a.set(n,e),W(e)||G(e,`<${e.tagName.toLowerCase()}> inside <${t.tagNames.head}>`,`<${t.tagNames.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.`)):(s?.remove(),a.delete(n))}}}function pt(e=customElements){e.get(t.tagNames.layout)||e.define(t.tagNames.layout,h),e.get(t.tagNames.layoutOutlet)||e.define(t.tagNames.layoutOutlet,p),e.get(t.tagNames.outlet)||e.define(t.tagNames.outlet,c),e.get(t.tagNames.route)||e.define(t.tagNames.route,o),e.get(t.tagNames.router)||e.define(t.tagNames.router,rt),e.get(t.tagNames.link)||e.define(t.tagNames.link,lt),e.get(t.tagNames.head)||e.define(t.tagNames.head,mt)}var gt;await void pt(gt);
1
+ const t={tagNames:{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"},enableShadowRoot:!1,basenameFileExtensions:[".html"]};function e(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function a(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}class n extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}}const s={int:{typeName:"int",pattern:/^-?\d+$/,parse(t){if(this.pattern.test(t))return parseInt(t,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(t){if(this.pattern.test(t))return parseFloat(t)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(t){if(this.pattern.test(t))return"true"===t||"1"===t}},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(t){if(this.pattern.test(t))return t}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(t){if(this.pattern.test(t))return t}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(t){if(!this.pattern.test(t))return;const[e,a,n]=t.split("-").map(Number),s=new Date(e,a-1,n);return s.getFullYear()===e&&s.getMonth()===a-1&&s.getDate()===n?s:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(t){if(this.pattern.test(t))return t}}},i={static:2,param:1,"catch-all":0};class r 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(t){super(),this._target=t??this}get parentCore(){return this._parentCore}set parentCore(t){this._parentCore=t}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,n){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&a(`${t.tagNames.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&a(`${t.tagNames.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?e(this._parentCore):n()}get absolutePath(){return this._checkParentCore(t=>{const e=t.absolutePath;return e.endsWith("/")?e+this._path:e+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(t=>[...t.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 t=[];for(const e of this._segmentInfos)e.paramName&&t.push(e.paramName);this._paramNames=t}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(t=>[...t.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let t=0;for(const e of this._segmentInfos)t+=i[e.type];this._weight=t}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(t=>t.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let t=0;for(const e of this._segmentInfos)"catch-all"!==e.type&&t++;this._segmentCount=""===this._path?0:t}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(t=>t.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(t,e={}){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=t,this._name=e.name||"",this._isFallbackRoute=e.isFallback||!1,e.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const a=t.split("/");for(let t=0;t<a.length;t++){const n=a[t];if(!(""===n&&t===a.length-1&&t>0)){if("*"===n){this._segmentInfos.push({type:"catch-all",segmentText:n,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(n.startsWith(":")){const t=n.match(/^:([^()]+)(\(([^)]+)\))?$/);let e,a="any";t?(e=t[1],t[3]&&Object.keys(s).includes(t[3])&&(a=t[3])):e=n.substring(1),this._segmentInfos.push({type:"param",segmentText:n,paramName:e,pattern:new RegExp("^([^\\/]+)$"),paramType:a})}else""===n&&e.isIndex||this._segmentInfos.push({type:"static",segmentText:n,paramName:null,pattern:new RegExp(`^${n}$`)})}}this._hasGuard=e.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",this._waitForSetGuardHandler=new Promise(t=>{this._resolveSetGuardHandler=t}))}setParams(t,e){const a=this._active;this._params=t,this._typedParams=e,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:t,typedParams:e},bubbles:!0})),a||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const t=this._active;this._params={},this._typedParams={},this._active=!1,t&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(t){for(const e of this.paramNames)if(this._params[e]!==t[e])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||a(`${t.tagNames.route} has no guardHandler.`),this._guardHandler}set guardHandler(t){this._guardHandler=t,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(t){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const e=t.path,a=t.lastPath;if(!await this._guardHandler(e,a))throw new n("Navigation cancelled by guard.",this._guardFallbackPath)}else if(this._hasGuard&&this._guardHandlerLoadFailed)throw new n("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath)}}class o extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=e();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new r(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||a(`${t.tagNames.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t){for(this._childNodeArray=[...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(t){this._core.guardHandler=t}setParams(t,e){this._core.setParams(t,e)}clearParams(){this._core.clearParams()}shouldChange(t){return this._core.shouldChange(t)}async guardCheck(t){return this._core.guardCheck(t)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(e,n){if(this._initialized)return;let s;this._initialized=!0;let i=!1,r=!1;this.hasAttribute("path")?s=this.getAttribute("path")||"":this.hasAttribute("index")?(s="",i=!0):this.hasAttribute("fallback")?(s="",r=!0):a(`${t.tagNames.route} should have a "path" or "index" attribute.`),this._routerNode=e,this._routeParentNode=n;const o=n||e;o.routeChildNodes.push(this),this._childIndex=o.routeChildNodes.length-1,r&&(n&&a(`${t.tagNames.route} with fallback attribute must be a direct child of ${t.tagNames.router}.`),e.fallbackRoute&&a(`${t.tagNames.router} can have only one fallback route.`),e.fallbackRoute=this),n&&(this._core.parentCore=n._core),this._core.parsePath(s,{isIndex:i,isFallback:r,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}}const l=new Map;class h extends HTMLElement{_uuid=e();constructor(){super()}async _loadTemplateFromSource(e){try{const n=await fetch(e);n.ok||a(`${t.tagNames.layout} failed to fetch layout from source: ${e}, status: ${n.status}`);const s=await n.text();return l.set(e,s),s}catch(n){a(`${t.tagNames.layout} failed to load layout from source: ${e}, error: ${n}`,{cause:n})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const e=this.getAttribute("src"),a=this.getAttribute("layout");e&&a&&console.warn(`${t.tagNames.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(e)l.has(e)?n.innerHTML=l.get(e)||"":n.innerHTML=await this._loadTemplateFromSource(e)||"";else if(a){const e=this._loadTemplateFromDocument(a);e?n.innerHTML=e:console.warn(`${t.tagNames.layout} could not find template with id "${a}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&t.enableShadowRoot}get name(){return this.getAttribute("name")||""}}class c extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||a(`${t.tagNames.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&t.enableShadowRoot}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const u=new Set(["props","states","attr",""]);function d(t,e,a){for(const[n,s]of Object.entries(e))switch(a){case"props":t.props={...t.props,[n]:s};break;case"states":t.states={...t.states,[n]:s};break;case"attr":null==s?t.removeAttribute(n):t.setAttribute(n,String(s));break;case"":t[n]=s}}function m(t,e){t.hasAttribute("data-bind")||a(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";u.has(n)||a(`${t.tagName} has invalid 'data-bind' attribute: ${n}`);const s=n,i=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const a=t.getAttribute("is");return a&&a.includes("-")?a:null}(t);i&&void 0===customElements.get(i)?customElements.whenDefined(i).then(()=>{t.isConnected&&d(t,e,s)}).catch(()=>{a(`Failed to define custom element: ${i}`)}):d(t,e,s)}class p extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||a(`${t.tagNames.layoutOutlet} has no layout.`),this._layout}set layout(t){this._layout=t,this.setAttribute("name",t.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 t of Array.from(this.layout.childNodes))this._layoutChildNodes.push(t),this.appendChild(t)}else{const a=e.content.cloneNode(!0),n=new Map;a.querySelectorAll("slot").forEach(e=>{const a=e.getAttribute("name")||"";n.has(a)?console.warn(`${t.tagNames.layoutOutlet} duplicate slot name "${a}" in layout template.`):n.set(a,e)});const s=new Map,i=document.createDocumentFragment();for(const t of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(t),t instanceof Element){const e=t.getAttribute("slot")||"";if(e.length>0&&n.has(e)){s.has(e)||s.set(e,document.createDocumentFragment()),s.get(e)?.appendChild(t);continue}}i.appendChild(t)}for(const[t,e]of n){const a=s.get(t);a&&e.replaceWith(a)}const r=n.get("");r&&r.replaceWith(i),this.appendChild(a)}}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(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{m(e,t)}),e.hasAttribute("data-bind")&&m(e,t))}}function g(){return document.createElement(t.tagNames.layoutOutlet)}const _="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";async function f(t,e){let n=null,s=null;const i=e.uuid||"",r=`\n//# sourceURL=${i?`wcs-guard-handler:${i}`:"wcs-guard-handler"}\n`,o=t.text+r;let l=!1;const h=t=>{t.effectiveDirective.startsWith("script-src")&&(l=!0)};document.addEventListener("securitypolicyviolation",h);try{if("function"==typeof URL.createObjectURL){const t=new Blob([o],{type:"application/javascript"}),e=URL.createObjectURL(t);try{n=await import(e)}catch(t){s=t}finally{URL.revokeObjectURL(e)}}if(!n){const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(o)));try{n=await import(`data:application/javascript;base64,${t}`)}catch(t){a(function(t,e,a){return a?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL, so script-src must allow blob:. See ${_}`:`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"")+`. If this page sets a Content-Security-Policy, see ${_}`}(t,s,l),{cause:s??t})}}}finally{document.removeEventListener("securitypolicyviolation",h)}return n&&"function"==typeof n.default?n.default:null}function b(t,e){f(t,e).then(t=>{t?e.guardHandler=t:e.notifyGuardHandlerLoadFailed()}).catch(t=>{console.error("loadGuardHandler failed:",t),e.notifyGuardHandlerLoadFailed()})}function y(t,e){let a=t.get(e.absolutePath);a||(a=[]);for(const t of a)if(!e.testAncestorNode(t)){console.warn(`Duplicate route path detected: '${e.absolutePath}' (defined as '${e.path}')`);break}a.push(e),1===a.length&&t.set(e.absolutePath,a)}async function w(e,a,n,s){const i=n.length>0?n[n.length-1]:null,r=document.createDocumentFragment(),o=Array.from(a.childNodes);for(const a of o)if(a.nodeType===Node.ELEMENT_NODE){let o=a,l=a;const h=l.tagName.toLowerCase();if(h===t.tagNames.route){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const a=document.importNode(l,!0);customElements.upgrade(a),a.appendChild(t);const r=a;r.initialize(e,i),y(s,r),n.push(r),o=r.placeHolder,l=r}else{if(h===t.tagNames.guardHandler){if(n.length>0){const t=n[n.length-1],e=l.querySelector('script[type="module"]');e&&b(e,t)}continue}if("template"===h){r.appendChild(l);continue}if(h===t.tagNames.layout){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const e=document.importNode(l,!0);customElements.upgrade(e),e.appendChild(t);const a=e,n=g();n.layout=a,o=n,l=e}}const c=await w(e,l,n,s);l.innerHTML="",l.appendChild(c),r.appendChild(o)}else r.appendChild(a);return r}async function N(t){const e=new Map;return await w(t,t.template.content,[],e)}function v(t,e){if("title"===t.announcePolicy){const e=t.a11yRegion;null!==e&&(e.textContent=document.title)}if("heading"===t.focusPolicy){const t=function(t){for(const e of t){if(e.nodeType!==Node.ELEMENT_NODE)continue;const t=e;if(/^H[1-6]$/.test(t.tagName)){if(C(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(C(e))return e}return null}(e.routes[e.routes.length-1].childNodeArray);if(null!==t)t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1"),t.focus();else{const t=document.querySelector("[autofocus]");null!==t?t.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}function C(t){return!1!==t.checkVisibility?.()}function P(t,e,a,n){const i=function(t,e,a){const n={},i={};let r=!0,o=!1,l=0,h=0;for(;l<t.absoluteSegmentInfos.length;){const e=t.absoluteSegmentInfos[l];if(e.isIndex){l++;continue}if(0===l&&""===e.segmentText&&"static"===e.type){l++;continue}const c=a[h];if(void 0===c){r=!1;break}let u=!1;if("param"===e.type){const t=e.paramType||"any",a=s[t].parse(c);void 0!==a&&(e.paramName&&(n[e.paramName]=c,i[e.paramName]=a),u=!0)}else u=null!==e.pattern.exec(c);if(!u){r=!1;break}if("catch-all"===e.type){const t=a.slice(h).join("/");n["*"]=t,i["*"]=t,o=!0;break}l++,h++}let c=!1;return r&&(o||l===t.absoluteSegmentInfos.length&&h===a.length)&&(c=!0),c?{path:e,routes:t.routes,params:n,typedParams:i,lastPath:""}:null}(t,e,a);i&&n.push(i);for(const s of t.routeChildNodes)P(s,e,a,n)}function E(t,e){const a=t.routeChildNodes,n=[],s=e.split("/"),i=s.filter((t,e)=>(0!==e||""!==t)&&!(e===s.length-1&&""===t&&s.length>1));for(const t of a)P(t,e,i,n);return n.sort((t,e)=>{const a=t.routes.at(-1),n=e.routes.at(-1),s=a.absoluteSegmentCount-n.absoluteSegmentCount;if(0!==s)return-s;const i=a.absoluteWeight-n.absoluteWeight;if(0!==i)return-i;return a.childIndex-n.childIndex}),n.length>0?n[0]:null}let A=null,k=null;function S(){const e=t.basenameFileExtensions;return 0===e.length?null:(A===e&&k||(A=e,k=new RegExp(`\\/[^/]+(?:${e.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),k)}function $(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const a=S();return a&&(e=e.replace(a,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function x(t,e){let a=t;return""!==e&&(t===e?a="":t.startsWith(e+"/")&&(a=t.slice(e.length))),""===a?"/":a}function R(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const a=S();return a&&(e=e.replace(a,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function L(t){t.clearParams();for(const e of t.childNodeArray)e.parentNode?.removeChild(e)}function H(e,a){const n={},s={};for(const t of e.paramNames)n[t]=a.params[t],s[t]=a.typedParams[t];e.setParams(n,s);for(const a of e.childNodeArray)if(a.nodeType===Node.ELEMENT_NODE){const n=a;n.querySelectorAll("[data-bind]").forEach(t=>{m(t,e.typedParams)}),n.hasAttribute("data-bind")&&m(n,e.typedParams),n.querySelectorAll(t.tagNames.layoutOutlet).forEach(t=>{t.assignParams(e.typedParams)}),n.tagName.toLowerCase()===t.tagNames.layoutOutlet&&n.assignParams(e.typedParams)}}function z(t,e){H(t,e);const a=t.placeHolder.parentNode,n=t.placeHolder.nextSibling;for(const e of t.childNodeArray)n?a?.insertBefore(e,n):a?.appendChild(e);return!0}const I=Symbol.for("wcstack.transition-runner");function T(t,e,a){const n=function(t){const e=globalThis[I];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}(t);if(null!==n)return n.run(e,{source:t,types:a});e()}const F=Symbol.for("wcstack.binder");function M(){const t=globalThis[F];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const O=Symbol.for("wcstack.binder.pending"),U=Symbol.for("wcstack.binder.taken");function W(){const t=globalThis;let e=t[U];return void 0===e&&(e=new WeakSet,t[U]=e),e}function D(t){const e=M();return null===e?(function(){const t=globalThis;let e=t[O];return void 0===e&&(e=[],t[O]=e),e}().push(t),!1):(W().add(t),e.bind(t),!0)}const j=new WeakSet,G="data-wcs";function B(t,e,a){!j.has(t)&&function(t){return t.hasAttribute(G)||null!==t.querySelector(`[${G}]`)}(t)&&(j.add(t),function(t){if("complete"!==document.readyState)return void window.addEventListener("load",t,{once:!0});t()}(()=>{var n;null!==M()||(n=t,W().has(n))||console.warn(`[@wcstack/router] ${e} contains ${G} 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. ${a}`)}))}function q(t){for(const e of t.childNodeArray)1===e.nodeType&&(D(e)||B(e,`<${e.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 K(t,e){try{for(const t of e.routes)await t.guardCheck(e)}catch(e){if(e instanceof n)return console.warn(`Navigation cancelled: ${e.message}. Redirecting to ${e.fallbackPath}`),queueMicrotask(()=>{t.navigate(e.fallbackPath).catch(t=>{console.error("Fallback navigation failed:",t)})}),!1;throw e}return!0}async function V(e,n,s,i,r=""){const o=x(s,e.basename);if(e.isSameMatch(o))return e.commitNavigation({params:e.params,typedParams:e.typedParams,routeName:e.routeName,search:r,path:o}),!0;let l=E(e,o);l||(e.fallbackRoute?l={routes:[e.fallbackRoute],params:{},typedParams:{},path:o,lastPath:i}:a(`${t.tagNames.router} No route matched for path: ${o}`)),l.lastPath=i;const h=n.lastRoutes,c=await async function(t,e,a){if(!await K(t,e))return!1;const n=new Set(e.routes),s=new Set(a),i=()=>{for(const t of a)n.has(t)||L(t);let t=!1;for(const n of e.routes)(!s.has(n)||n.shouldChange(e.params)||t)&&(t=z(n,e),a.length>0&&!s.has(n)&&q(n))};let r;return 0===a.length?i():r=T("router",i),void 0!==r&&await r,!0}(e,l,h);return!!c&&(e.commitNavigation({params:l.params,typedParams:l.typedParams,routeName:l.routes[l.routes.length-1]?.name??"",search:r,path:o}),n.lastRoutes=l.routes,h.length>0&&v(e,l),!0)}function Y(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function J(t,e){const a=Object.keys(t),n=Object.keys(e);if(a.length!==n.length)return!1;for(const n of a){if(!Object.prototype.hasOwnProperty.call(e,n))return!1;if(t[n]!==e[n])return!1}return!0}function Q(t){let e=t,a="";const n=e.indexOf("#");n>=0&&(a=e.slice(n),e=e.slice(0,n));let s="";const i=e.indexOf("?");return i>=0&&(s=e.slice(i),e=e.slice(0,i)),{pathname:e,search:s,hash:a}}function X(t){return"?"===t?"":t}function Z(t,e){let a=Object.getPrototypeOf(t);for(;null!==a;){const t=Object.getOwnPropertyDescriptor(a,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;a=Object.getPrototypeOf(a)}return!1}function tt(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const et="data-wcs-ssr",at="data-wcs-ssr-link",nt="@@wcs-route-ph:",st="@@wcs-route-start:",it="@@wcs-route-end:",rt=Object.freeze({});class ot 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:t=>t.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=rt;_typedParams=rt;_searchParams=rt;_routeName="";_hasCommitted=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),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 t=document.createElement("div");t.setAttribute("role","status"),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.clipPath="inset(50%)",t.style.whiteSpace="nowrap",this.appendChild(t),this._a11yRegion=t}_normalizePathname(t){return $(t)}_normalizeBasename(t){return R(t)}_joinInternalPath(t,e){const a=this._normalizeBasename(t);let n=e.startsWith("/")?e:"/"+e;return n=this._normalizePathname(n),a?"/"===n?a+"/":a+n:n}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let t=new URL(document.baseURI).pathname||"/";return"/"===t?"":this._normalizeBasename(t)}get basename(){return this._basename}_getOutlet(){const e=this.nextElementSibling;if(e&&e.matches(t.tagNames.outlet))return e;const a=document.createElement(t.tagNames.outlet);return this.parentNode?this.parentNode.insertBefore(a,this.nextSibling):document.body.appendChild(a),a}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||a(`${t.tagNames.router} has no outlet.`),this._outlet}get template(){return this._template||a(`${t.tagNames.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(t){const e=this._path!==t;this._path=t,e&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t){const e=Object.freeze({...t.params}),a=Object.freeze({...t.typedParams}),n=function(t){const e={};for(const[a,n]of new URLSearchParams(t))e[a]=n;return Object.freeze(e)}(t.search),s=!J(this._params,e),i=this._routeName!==t.routeName,r=!J(this._searchParams,n),o=this._path!==t.path;s&&(this._params=e,this._typedParams=a),i&&(this._routeName=t.routeName),r&&(this._searchParams=n),this._path=t.path,this._hasCommitted=!0,s&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),i&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),r&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),o&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t.path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(t){this._fallbackRoute=t}get navigateUrl(){return this._navigateUrl}set navigateUrl(e){null!=e&&""!==e&&this._navigateUrl!==e&&(this._navigateUrl=e,this.navigate(e).catch(e=>{console.error(`${t.tagNames.router} navigate failed:`,e)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(e){null!=e&&""!==e&&this._replaceUrl!==e&&(this._replaceUrl=e,this.replace(e).catch(e=>{console.error(`${t.tagNames.router} replace failed:`,e)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(t){await this._performNavigation(t,!1)}async replace(t){await this._performNavigation(t,!0)}async _performNavigation(t,e){const a=Q(t),n=""!==a.pathname||""===a.search&&""===a.hash?this._joinInternalPath(this._basename,a.pathname):window.location.pathname,s=n+X(a.search)+a.hash,i=Y();if(i?.navigate){const t=e?i.navigate(s,{history:"replace"}):i.navigate(s);await(t?.finished)}else{e?history.replaceState(null,"",s):history.pushState(null,"",s);const t=this._normalizePathname(n),i=this.isSameMatch(x(t,this._basename));await V(this,this.outlet,t,this._path,X(a.search))&&!i&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||(t===this._basename||t.startsWith(this._basename+"/"))}_onNavigateFunc(e){if(!e.canIntercept||e.hashChange||null!==e.downloadRequest)return;const a=new URL(e.destination.url),n=this._normalizePathname(a.pathname);if(!this._isOwnPath(n))return;const s=this.isSameMatch(x(n,this._basename)),i=s&&("push"===e.navigationType||"replace"===e.navigationType),r=a.search,o=this;e.intercept({handler:async()=>{try{await V(o,o.outlet,n,o.path,r)}catch(e){throw console.error(`${t.tagNames.router} applyRoute failed:`,e),e}},scroll:i?"manual":"after-transition",focusReset:s||null!==o.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await V(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const e=tt();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const n=null!==document.querySelector("base[href]"),s=new URL(window.location.href);""!==this._basename||n||"/"===s.pathname||a(`${t.tagNames.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||a(`${t.tagNames.router} should have a <template> child element.`);const i=e?this._template.content.cloneNode(!0):null,r=await N(this),o=!e&&this._outlet.hasAttribute(et);if(o||this._outlet.rootNode.appendChild(r),null!==i){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(i)}0===this.routeChildNodes.length&&a(`${t.tagNames.router} has no route definitions.`),e||this._ensureA11yRegion();const l=this._normalizePathname(window.location.pathname);if(e)return await this._renderForSsr(l),void(this._initialized=!0);if(o){if(await this._hydrateFromSsr(l))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(et);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(r)}await V(this,this.outlet,l,this._path,window.location.search||""),(o||null!==M())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(e){const a=this.outlet.rootNode,n=new Map;let s=!1;if(this._forEachRoute(t=>{n.has(t.absolutePath)?s=!0:n.set(t.absolutePath,t)}),s)return!1;if(null!==a.querySelector(t.tagNames.layoutOutlet))return!1;const i=new Map,r=new Map,o=new Map,l=document.createTreeWalker(a,NodeFilter.SHOW_COMMENT);let h=0;for(;l.nextNode();){const t=l.currentNode,e=t.data;if(h++,e.startsWith(nt)){const a=e.slice(15);if(i.has(a)||!n.has(a))return!1;i.set(a,t)}else if(e.startsWith(st)){const a=e.slice(18);if(r.has(a)||!n.has(a))return!1;r.set(a,{comment:t,index:h})}else if(e.startsWith(it)){const a=e.slice(16);if(o.has(a)||!n.has(a))return!1;o.set(a,{comment:t,index:h})}}if(r.size!==o.size)return!1;const c=[];for(const[t,e]of r){const a=o.get(t);if(!a)return!1;if(a.comment.parentNode!==e.comment.parentNode)return!1;if(a.index<=e.index)return!1;c.push({start:e.index,end:a.index})}for(const t of c)for(const e of c)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const u=x(e,this._basename);let d=E(this,u);if(!d){if(null===this._fallbackRoute)return!1;d={routes:[this._fallbackRoute],params:{},typedParams:{},path:u,lastPath:this._path}}if(d.lastPath=this._path,d.routes.length!==r.size)return!1;for(const t of d.routes)if(!r.has(t.absolutePath))return!1;const m=new Set;for(const t of this.routeChildNodes)m.add(t.absolutePath);for(const t of d.routes)for(const e of t.routeChildNodes)m.add(e.absolutePath);if(i.size!==m.size)return!1;for(const t of m)if(!i.has(t))return!1;for(const[t,e]of i){const a=n.get(t);e.parentNode.replaceChild(a.placeHolder,e)}for(const e of d.routes){const a=r.get(e.absolutePath).comment,n=o.get(e.absolutePath).comment,s=[],i=new Set;let l=a.nextSibling;for(;null!==l&&l!==n;){if(l.nodeType===Node.COMMENT_NODE){const t=l.data;if(t.startsWith(st)){const e=t.slice(18);l=o.get(e).comment.nextSibling;continue}}if(i.has(l))l=l.nextSibling;else{if(l.nodeType===Node.ELEMENT_NODE&&l.tagName.toLowerCase()===t.tagNames.link){const t=l.anchorElement;null!==t&&i.add(t)}s.push(l),l=l.nextSibling}}e.adoptChildNodes(s)}for(const{comment:t}of r.values())t.remove();for(const{comment:t}of o.values())t.remove();this.outlet.removeAttribute(et);for(const t of d.routes)H(t,d);return this.outlet.lastRoutes=d.routes,!await K(this,d)||(this.commitNavigation({params:d.params,typedParams:d.typedParams,routeName:d.routes[d.routes.length-1].name,search:window.location.search||"",path:u}),!0)}async _renderForSsr(e){const n=x(e,this._basename),s=E(this,n),i=s?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===i.length&&a(`${t.tagNames.router} No route matched for path: ${n}`),!i.some(t=>t.hasGuard)){await V(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${nt}${t.absolutePath}`}),this.outlet.setAttribute(et,"");for(const t of this.outlet.lastRoutes){const e=t.placeHolder.parentNode,a=t.childNodeArray,n=document.createComment(`${st}${t.absolutePath}`),s=document.createComment(`${it}${t.absolutePath}`);e.insertBefore(n,a[0]??t.placeHolder.nextSibling);const i=a[a.length-1];e.insertBefore(s,i?i.nextSibling:n.nextSibling)}}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&D(e)}_forEachRoute(t,e=this){for(const a of e.routeChildNodes)t(a),this._forEachRoute(t,a)}async connectedCallback(){if(function(t){const e=t.constructor?.wcBindable,a=e?.inputs;if(void 0!==a)for(const e of a){const a=e.name;if(!Object.prototype.hasOwnProperty.call(t,a))continue;if(!Z(t,a))continue;const n=t,s=n[a];delete n[a],n[a]=s}}(this),tt()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const t=Y();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(Y()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const lt=["title","rel","target","download","hreflang","lang","dir"];class ht extends HTMLElement{static get observedAttributes(){return["to",...lt]}_childNodeArray=[];_uuid=e();_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(t.tagNames.router);if(e)return this._router=e;const n=this.getRootNode(),s=n.querySelector?.(t.tagNames.router);if(s)return this._router=s;a(`${t.tagNames.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(t){return $(t)}_joinInternalPath(t,e){const a=R(t),n=e.startsWith("/")?e:"/"+e,s=this._normalizePathname(n);return a?"/"===s?a+"/":a+s:s}_isInternalTarget(t){return t.startsWith("/")||t.startsWith("?")}_setAnchorHref(e,n){if(this._isInternalTarget(n)){const{pathname:t,search:a,hash:s}=Q(n),i=""===t?window.location.pathname:this._joinInternalPath(this.router.basename,t);e.href=i+X(a)+s}else try{e.href=new URL(n).toString()}catch{a(`[${t.tagNames.link}] Invalid URL in 'to' attribute: ${n}`)}}connectedCallback(){tt()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(at)?t:null}_connect(){this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let a;if(null!==e)a=e,a.removeAttribute(at),this._childNodeArray=Array.from(a.childNodes),this._setAnchorHref(a,this._path);else{const e=this.nextSibling;a=document.createElement("a"),this._setAnchorHref(a,this._path);for(const t of Array.from(this.attributes))(t.name.startsWith("aria-")||lt.includes(t.name))&&a.setAttribute(t.name,t.value);for(const t of this._childNodeArray)a.appendChild(t);e?t.insertBefore(a,e):t.appendChild(a)}if(this._anchorElement=a,tt())return this._updateActiveState(),void a.setAttribute(at,"");Y()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!Y()?.navigate&&(this._onClick=async t=>{t.defaultPrevented||0===t.button&&(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||this._isInternalTarget(this._path)&&(t.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},a.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){Y()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const t=this._anchorElement;t&&(this._onClick&&(t.removeEventListener("click",this._onClick),this._onClick=void 0),t.remove(),this._anchorElement=null);for(const e of this._childNodeArray)t&&e.parentNode===t&&t.removeChild(e);this._router=null}attributeChangedCallback(t,e,a){if("to"===t&&e!==a)this._path=a||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(lt.includes(t)){const e=this._anchorElement;e&&(null===a?e.removeAttribute(t):e.setAttribute(t,a))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const t=this._normalizePathname(new URL(window.location.href).pathname),{pathname:e}=Q(this._path),a=this._normalizePathname(this._isInternalTarget(this._path)?""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e):e);this._anchorElement&&(t===a?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current","page")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const ct=[],ut=new Map;let dt=!1;const mt=new WeakMap;class pt 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 t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),dt||(this._captureInitialHead(),dt=!0),ct.push(this),this._reapplyHead()}disconnectedCallback(){const t=ct.indexOf(this);-1!==t&&ct.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||a("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=mt.get(t);if(void 0!==e)return e;const a=this._computeKey(t);return mt.set(t,a),a}_computeKey(t){const e=t.tagName.toLowerCase();if("title"===e)return"title";if("meta"===e){return`meta:${t.getAttribute("name")||""}:${t.getAttribute("property")||""}:${t.getAttribute("http-equiv")||""}:${t.hasAttribute("charset")?"charset":""}:${t.getAttribute("media")||""}`}if("link"===e){return`link:${t.getAttribute("rel")||""}:${t.getAttribute("href")||""}:${t.getAttribute("media")||""}:${t.getAttribute("hreflang")||""}`}if("base"===e)return"base";if("script"===e){const e=t.getAttribute("src")||"",a=t.getAttribute("id")||"",n=t.getAttribute("type")||"";return e||a?`script:${e}:${a}:${n}`:`script::${n}:${t.outerHTML.slice(0,100)}`}if("style"===e){const e=t.getAttribute("id")||"",a=t.getAttribute("media")||"";return e?`style:${e}:${a}`:`style::${a}:${t.outerHTML.slice(0,100)}`}return`${e}:${t.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const t=new Map;for(const e of Array.from(document.head.children)){const a=this._getKey(e);t.has(a)||t.set(a,e)}return t}_captureInitialHead(){const t=document.head;for(const e of Array.from(t.children)){const t=this._getKey(e);ut.has(t)||ut.set(t,e.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of ct)for(const a of t._childElementArray)e.add(this._getKey(a));for(const t of ut.keys())e.add(t);const a=this._buildHeadElementMap();for(const t of a.keys())e.add(t);for(const n of e){let e=null;for(let t=ct.length-1;t>=0;t--){const a=ct[t];for(const t of a._childElementArray)if(this._getKey(t)===n){e=t.cloneNode(!0);break}if(e)break}if(!e&&ut.has(n)){e=ut.get(n).cloneNode(!0)}const s=a.get(n)??null;e?(s?s.replaceWith(e):document.head.appendChild(e),a.set(n,e),D(e)||B(e,`<${e.tagName.toLowerCase()}> inside <${t.tagNames.head}>`,`<${t.tagNames.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.`)):(s?.remove(),a.delete(n))}}}function gt(e=customElements){e.get(t.tagNames.layout)||e.define(t.tagNames.layout,h),e.get(t.tagNames.layoutOutlet)||e.define(t.tagNames.layoutOutlet,p),e.get(t.tagNames.outlet)||e.define(t.tagNames.outlet,c),e.get(t.tagNames.route)||e.define(t.tagNames.route,o),e.get(t.tagNames.router)||e.define(t.tagNames.router,ot),e.get(t.tagNames.link)||e.define(t.tagNames.link,ht),e.get(t.tagNames.head)||e.define(t.tagNames.head,pt)}var _t;await void gt(_t);
2
2
  //# sourceMappingURL=auto.min.js.map