@wcstack/router 3.4.0 → 3.5.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
@@ -117,17 +117,23 @@
117
117
 
118
118
  1.32 以降は 2 つの形がどちらも動きますが、交換可能ではありません。プロジェクト単位でなく、ページごとに選びます。
119
119
 
120
- **既定: 本文を `<wcs-route>` の中に置く。** router が入場時にスタンプし、退場時に取り除きます。中の `data-wcs` バインディングはスタンプ時に束ねられる(binder プロトコル)ので、state が描画するマークアップ —— `for:`・`if:`・テキスト —— も他の場所と同じように動きます。router が提供するものはすべてルート本文を基準にしています: ルートごとの `<wcs-head>`、`focus="heading"` / `announce=` ポリシー(*スタンプされた内容の中の*見出しを探す)、ルート切替ごとのビュートランジション。
120
+ **既定: 本文を `<wcs-route>` の中に置く。** router が入場時にスタンプし、退場時に取り除きます。中の `data-wcs` バインディングはスタンプ時に束ねられる(binder プロトコル)ので、state が描画するマークアップ —— `for:`・`if:`・テキスト —— も他の場所と同じように動きます。router が提供するものはすべてルート本文を基準にしています: ルートごとの `<wcs-head>`、`focus="heading"` / `announce=` ポリシー(*スタンプされた内容の中の*見出しを探す)、ルート切替ごとのビュートランジション。router が state に渡すのはルート本文の要素だけなので、`<wcs-route>` の直下の(要素に包まれていない)テキストの `{{ }}` が束ねられるのは、着地のルートで state の最初の走査が見つけたときだけで、ナビゲーションで入ったときは束ねられません。そうしたテキストは要素で包みます(`<p>{{ title }}</p>`)。
121
121
 
122
122
  ```html
123
123
  <wcs-route path="/products/:productId(int)">
124
124
  <wcs-head><title data-wcs="textContent: product.name"></title></wcs-head>
125
- <h2 data-wcs="textContent: product.name"></h2>
126
- <template data-wcs="for: product.variants"><li data-wcs="textContent: .name"></li></template>
125
+ <article>
126
+ <h2 data-wcs="textContent: product.name"></h2>
127
+ <ul><template data-wcs="for: product.variants"><li data-wcs="textContent: .name"></li></template></ul>
128
+ </article>
127
129
  </wcs-route>
128
130
  ```
129
131
 
130
- **例外: DOM をナビゲーションより長生きさせたいときは state で切り替える(`<template data-wcs="if: …">`)。** スタンプは破棄を伴います —— ルート本文は入場のたびに作り直されます —— ので、再生中の `<video>`、入力途中のフォーム、スクロール済みのリスト、描画済みの `<canvas>` は、離れて戻ってくると生き残りません。そうした内容は router の外に置き、router の `routeName` / `typedParams` 出力が立てる state のフラグにバインドし、ルート要素は空(または `<wcs-head>` だけ)にします。
132
+ 構造のテンプレート(`for:` / `if:`)は、上の `<ul>` のようにルート本文の要素の中に置きます。`<wcs-route>` の直下に置いたものが描かれるのは、state のページの最初の走査のときだけです(着地のルートで、router がスタンプした後に state が読み込みを終えたとき)。ナビゲーションで入ったルートは内容を state に渡し、@wcstack/state 3.x は、渡された構造のテンプレートそのものは描かず、束縛の適用の失敗として報告します。上の `<article>` のように本文を 1 つの要素で包めば避けられます。`data-wcs` を自分に持つ直下の要素を、テンプレートを含む要素より前に置く形(`<wcs-route>` の直下の `<h2 data-wcs="…">` の後ろに `<ul>` が続く形)は、@wcstack/state 3.5.1 以降では動きます。渡された要素だけを束ねるためです。3.5.0 以前はそうした要素を親から走査して束ねるので、まだ準備のできていない後ろのテンプレートに届き、ナビゲーションのときに同じ失敗を報告します。これらの版では、その本文も包んでください。
133
+
134
+ router は、スタンプしたルート本文の終わりにコメントの印 `<!--@@wcs-route-end:<path>-->`(SSR と同じ印)を置き、退場のときにルートの placeholder からこの印までをまとめて持ち出し、次の入場で戻します。ルート自身のノードのほか、その間に後から描かれたもの(着地のルートで直下のテンプレートが描いた行など)も含みます。作者のコードがこの 2 つのコメントの間に差し込んだノードはルートと一緒に出入りします。ルート本文から外へ移したノード(`<body>` へ移したダイアログなど)は、これまでどおり退場のときにルート本文へ戻して持ちます。戻すのは持ち出したものなので、作者のコードがルート本文から取り除いた直下のノード(閉じたお知らせなど)は、次の入場でも戻りません。印はコメントなので、`wcs-outlet:empty` には影響しません。
135
+
136
+ **例外: ナビゲーションをまたいで DOM を文書に置いたままにしたいときは state で切り替える(`<template data-wcs="if: …">`)。** ルートを離れると本文は文書から外され、入場のときに同じノードが戻されます。ノードが持つもの(入力途中のフォームの値)は残りますが、文書につながっていることが要るものは残りません。再生中の `<video>` は止まり、スクロール済みのリストはスクロール位置を失い(Chromium と WebKit)、`disconnectedCallback` で後始末する部品は初めからやり直します。そうした内容は router の外に置き、router の `routeName` / `typedParams` 出力が立てる state のフラグにバインドし、ルート要素は空(または `<wcs-head>` だけ)にします。
131
137
 
132
138
  ```html
133
139
  <wcs-router data-wcs="routeName: routeName">
@@ -271,7 +277,7 @@ interface IGuardContext { // 進入先マッチの frozen スナップ
271
277
  - 第 3 引数に進入先マッチ(`params` / `typedParams` / `searchParams` / `routeName`)が渡る。`toPath` / `fromPath` は basename スライス後のパス
272
278
  - `<wcs-route>` の外に配置された `<wcs-guard-handler>` は無視される
273
279
  - `<script type="module">` がない場合、`guardHandler` は設定されない
274
- - **Content-Security-Policy 下では**、ガードスクリプトは `blob:` URL 経由で評価されるため `script-src blob:` が必要。ガードはインライン専用で、`<wcs-state>` のような `src=` 退避経路は存在しない。詳細は [docs/csp.ja.md](../../docs/csp.ja.md)
280
+ - **Content-Security-Policy 下では**、ガードスクリプトは `blob:` URL 経由で評価されるため、router を読み込む `<script>` にページの nonce を付けるか(blob: の import がその nonce を引き継ぐ)、`script-src blob:` が必要(blob: の import が失敗すると router は `data:` URL で読み直すので `script-src data:` でも通るが、危険の大きい source なので開けないこと)。ガードはインライン専用で、`<wcs-state>` のような `src=` 退避経路は存在しない。詳細は [docs/csp.ja.md](../../docs/csp.ja.md)
275
281
  - **`require-trusted-types-for 'script'` 下では**、`<wcs-layout>` のテンプレート展開が `wcstack` という名前の Trusted Types policy を通るため、CSP に `trusted-types wcstack;` が必要(または自前の policy を注入する。詳細は [docs/csp.ja.md](../../docs/csp.ja.md) の §7)
276
282
 
277
283
  #### ルート commit 前のデータロード
@@ -357,6 +363,8 @@ console.log(router.typedParams.userId); // 123 (number)
357
363
 
358
364
  テンプレートを読み込み、子要素を`<slot>`へ挿入して`<wcs-layout-outlet>`へ書き出す。Light DOM対応。外部ファイル対応。
359
365
 
366
+ @wcstack/state と組むと、outlet は置いた要素を、ページに入った後で(テンプレートの読み込みは非同期)state の binder へ渡す。レイアウトのテンプレートと、スロットに入るルートの内容の、要素の中の `data-wcs` / `{{ }}` は、着地のルートだけでなく、ナビゲーションで初めてレイアウトに入ったときから束ねられる。渡すのは要素だけなので、レイアウトのテンプレートの直下の(要素に包まれていない)テキストの `{{ }}` は、ナビゲーションでは束ねられない。ルート本文と同じく要素で包むこと(「ルートの本文はどこに置くか」の節)。`enable-shadow-root` では、テンプレートは outlet の shadow root の中にあり、ページの state は束ねない(light DOM のルートの内容は束ねる)。
367
+
360
368
  | 属性 | 説明 |
361
369
  |------|------|
362
370
  | `layout` | テンプレートとなる`<template>`タグのid属性 |
@@ -469,7 +477,7 @@ a.active { font-weight: bold; color: blue; }
469
477
  </wcs-route>
470
478
  ```
471
479
 
472
- 定義済みの要素(組み込み要素、およびルート描画前に定義されたカスタム要素)では、パラメータは `connectedCallback` の発火前に割り当てられる。未定義のカスタム要素の場合、割り当ては `customElements.whenDefined()` の解決後まで遅延される。この解決はアップグレードの*後*に起こるため、アップグレード時に走る `connectedCallback` ではパラメータはまだ見えない。`props` / `states` / 属性の setter(または `attributeChangedCallback`)で受け取るか、ルート描画前に要素を定義しておく(例: `@wcstack/router` より先にスクリプトを読み込む)こと。
480
+ 定義済みの要素(組み込み要素、およびルート描画前に定義されたカスタム要素)では、パラメータは `connectedCallback` の発火前に割り当てられる。未定義のカスタム要素の場合、割り当ては `customElements.whenDefined()` の解決後まで遅延される。この解決はアップグレードの*後*に起こるため、アップグレード時に走る `connectedCallback` ではパラメータはまだ見えない。`props` / `states` / 属性の setter(または `attributeChangedCallback`)で受け取るか、ルート描画前に要素を定義しておく(例: `@wcstack/router` より先にスクリプトを読み込む)こと。パラメータだけが変わるナビゲーション(`/users/1` → `/users/2`)は、ルートの内容を取り出して同じ位置に戻すので、`connectedCallback` がもう一度(入れ子のルートでも 1 回だけ)走り、新しいパラメータが見える。
473
481
 
474
482
  ## 設定
475
483
 
@@ -496,6 +504,8 @@ bootstrapRouter({
496
504
  });
497
505
  ```
498
506
 
507
+ 知らないオプションや型の違う値(`tagNames` の知らないキーを含む)は、3.5 ではコンソールに警告を出し、4.0 では例外を投げます。
508
+
499
509
  ## ルート遷移アニメーション
500
510
 
501
511
  ルートの差し替えは素の `removeChild` / `insertBefore` なので、去っていくビューは自力では退場できない。ページに [`@wcstack/view-transition`](https://github.com/wcstack/wcstack/tree/main/packages/view-transition) を足すと、差し替えが View Transition の中で行われ、見た目は CSS で書ける。
package/README.md CHANGED
@@ -117,17 +117,23 @@ That's what `<wcs-router>`, `<wcs-route>`, and friends explore. One CDN import,
117
117
 
118
118
  Two shapes work since 1.32, and they are not interchangeable. Pick per page, not per project.
119
119
 
120
- **Default: put the content inside `<wcs-route>`.** The router stamps it on entry and removes it on exit. `data-wcs` bindings inside it are bound when it is stamped (the binder protocol), so state-rendered markup — `for:`, `if:`, text — works there like anywhere else. Everything the router offers is keyed to the route body: `<wcs-head>` per route, the `focus="heading"` / `announce=` policies (they look for the heading *in the stamped content*), and a view transition per route swap.
120
+ **Default: put the content inside `<wcs-route>`.** The router stamps it on entry and removes it on exit. `data-wcs` bindings inside it are bound when it is stamped (the binder protocol), so state-rendered markup — `for:`, `if:`, text — works there like anywhere else. Everything the router offers is keyed to the route body: `<wcs-head>` per route, the `focus="heading"` / `announce=` policies (they look for the heading *in the stamped content*), and a view transition per route swap. The router hands state only the route body's elements, so a `{{ }}` in text directly under `<wcs-route>` (not inside an element) is bound only on the landing route, by state's first scan — not when the route is entered by navigation. Wrap such text in an element (`<p>{{ title }}</p>`).
121
121
 
122
122
  ```html
123
123
  <wcs-route path="/products/:productId(int)">
124
124
  <wcs-head><title data-wcs="textContent: product.name"></title></wcs-head>
125
- <h2 data-wcs="textContent: product.name"></h2>
126
- <template data-wcs="for: product.variants"><li data-wcs="textContent: .name"></li></template>
125
+ <article>
126
+ <h2 data-wcs="textContent: product.name"></h2>
127
+ <ul><template data-wcs="for: product.variants"><li data-wcs="textContent: .name"></li></template></ul>
128
+ </article>
127
129
  </wcs-route>
128
130
  ```
129
131
 
130
- **Exception: switch it with state (`<template data-wcs="if: …">`) when the DOM must outlive the navigation.** Stamping is a teardown — a route body is rebuilt on every entry — so a `<video>` mid-playback, a half-filled form, a scrolled list, or a `<canvas>` you drew on does not survive leaving and coming back. Keep such content outside the router, bound to a state flag that the router's `routeName` / `typedParams` outputs set, and leave the route element empty (or holding only `<wcs-head>`).
132
+ Put a structural template (`for:` / `if:`) inside an element of the route body, as the `<ul>` above does. One directly under `<wcs-route>` is rendered only by state's first scan of the page — the landing route, when state finishes loading after the router stamped it. A route entered by navigation hands its content to state, and @wcstack/state 3.x does not render a structural template handed over itself: it reports that the binding failed to apply. Wrapping the body in one element, as the `<article>` above does, avoids that. A top-level element that carries `data-wcs` itself may come before the element that holds the template (an `<h2 data-wcs="…">` directly under `<wcs-route>`, followed by the `<ul>`) with @wcstack/state 3.5.1 and later, which bind only the element handed over. 3.5.0 and earlier bind such an element by walking from its parent, which reaches the later template before it is set up and reports the same failure on navigation; with those versions, wrap that body too.
133
+
134
+ The router marks where a stamped route body ends with a comment, `<!--@@wcs-route-end:<path>-->` (the same marker SSR uses), and on exit takes everything from the route's placeholder up to it along — the route's own nodes and whatever was rendered among them since, such as the rows a top-level template rendered on the landing route — and puts it all back on the next entry. A node your own code inserts between those two comments goes and comes back with the route; one you moved out of the route body (a dialog moved to `<body>`) is taken back into it on exit, as before. What comes back is what was taken out: a top-level node your code removed from the route body (a dismissed notice) stays removed on the next entry. The marker is a comment, so `wcs-outlet:empty` is unaffected.
135
+
136
+ **Exception: switch it with state (`<template data-wcs="if: …">`) when the DOM must stay in the document across the navigation.** Leaving a route removes its body from the document, and entering puts the same nodes back. What the nodes hold survives (a half-filled form keeps its input), but what needs them to stay connected does not: a `<video>` stops playing, a scrolled list loses its scroll position (in Chromium and WebKit), and a component that tears down in `disconnectedCallback` starts over. Keep such content outside the router, bound to a state flag that the router's `routeName` / `typedParams` outputs set, and leave the route element empty (or holding only `<wcs-head>`).
131
137
 
132
138
  ```html
133
139
  <wcs-router data-wcs="routeName: routeName">
@@ -271,7 +277,7 @@ Place as a child of `<wcs-route>` to declaratively define a guard decision funct
271
277
  - The third argument carries the match being entered (`params` / `typedParams` / `searchParams` / `routeName`); `toPath` / `fromPath` are basename-sliced paths
272
278
  - `<wcs-guard-handler>` placed outside a `<wcs-route>` is ignored
273
279
  - If no `<script type="module">` is present, `guardHandler` is not set
274
- - **Under a Content-Security-Policy**, the guard script is evaluated through a `blob:` URL, so `script-src blob:` is required. Guards are inline-only — there is no `src=` escape hatch as there is for `<wcs-state>`. See [docs/csp.md](../../docs/csp.md)
280
+ - **Under a Content-Security-Policy**, the guard script is evaluated through a `blob:` URL, so it needs either the page's nonce on the `<script>` that loads router (the blob: import inherits it) or `script-src blob:`. (Router retries through a `data:` URL when the blob: import fails, so `script-src data:` would also pass — do not open it; it is the riskier source.) Guards are inline-only — there is no `src=` escape hatch as there is for `<wcs-state>`. See [docs/csp.md](../../docs/csp.md)
275
281
  - **Under `require-trusted-types-for 'script'`**, `<wcs-layout>` expands its template through a Trusted Types policy named `wcstack`, so the CSP needs `trusted-types wcstack;` (or your own policy, injected as described in [docs/csp.md](../../docs/csp.md) section 7)
276
282
 
277
283
  #### Loading data before a route commits
@@ -357,6 +363,8 @@ console.log(router.typedParams.userId); // 123 (number)
357
363
 
358
364
  Loads a template, inserts children into `<slot>`, and writes to `<wcs-layout-outlet>`. Light DOM supported. External file supported.
359
365
 
366
+ With @wcstack/state, the outlet hands the elements it places — and with them the `data-wcs` / `{{ }}` inside elements of the layout template and of the route content in its slots — to state's binder once they are in the page (the template loads asynchronously), so both are bound on the very first navigation into the layout, not only on the landing route. Only elements are handed over: a `{{ }}` in text directly under the layout template (not inside an element) is not bound on a navigation — wrap it in an element, as for a route body (see "Where route content lives"). With `enable-shadow-root`, the template lives in the outlet's shadow root, which the page's state does not bind (the route content in the light DOM is bound).
367
+
360
368
  | Attribute | Description |
361
369
  |------|------|
362
370
  | `layout` | The id attribute of the template tag used as the template. |
@@ -469,7 +477,7 @@ Elements with the `data-bind` attribute automatically receive matched route para
469
477
  </wcs-route>
470
478
  ```
471
479
 
472
- For elements that are already defined (built-in elements and custom elements defined before the route renders), parameters are assigned before `connectedCallback` fires. For custom elements that are not yet defined, assignment is deferred until `customElements.whenDefined()` resolves — that happens *after* the upgrade, so the `connectedCallback` run by the upgrade does not see the parameters yet. Read them in the `props` / `states` / attribute setter (or in `attributeChangedCallback`) instead, or make sure the element is defined before the route is rendered (e.g. load its script before `@wcstack/router`).
480
+ For elements that are already defined (built-in elements and custom elements defined before the route renders), parameters are assigned before `connectedCallback` fires. For custom elements that are not yet defined, assignment is deferred until `customElements.whenDefined()` resolves — that happens *after* the upgrade, so the `connectedCallback` run by the upgrade does not see the parameters yet. Read them in the `props` / `states` / attribute setter (or in `attributeChangedCallback`) instead, or make sure the element is defined before the route is rendered (e.g. load its script before `@wcstack/router`). A navigation that changes only a parameter (`/users/1` → `/users/2`) takes the route's content out and puts it back in place, so `connectedCallback` runs again — once, in a nested route too — and sees the new parameters.
473
481
 
474
482
  ## Configuration
475
483
 
@@ -496,6 +504,8 @@ bootstrapRouter({
496
504
  });
497
505
  ```
498
506
 
507
+ Unknown or wrongly typed options (unknown `tagNames` keys included) log a console warning in 3.5 and throw in 4.0.
508
+
499
509
  ## Route transition animations
500
510
 
501
511
  Route swaps are a plain `removeChild` / `insertBefore` pair, so the outgoing view cannot animate out on its own. Adding [`@wcstack/view-transition`](https://github.com/wcstack/wcstack/tree/main/packages/view-transition) to the page makes the swap run inside a View Transition, which you then style in CSS:
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}}};function i(t){const e={};for(const[a,n]of new URLSearchParams(t))e[a]=n;return Object.freeze(e)}function r(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}const o={static:2,param:1,"catch-all":0};class l 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+=o[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,s=await this._guardHandler(e,a,function(t){return Object.freeze({params:Object.freeze({...t.params}),typedParams:Object.freeze({...t.typedParams}),searchParams:i(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof s&&""!==s)throw new n("Navigation cancelled by guard.",s);if(!s)throw new n("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof s?s:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new n("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}}class c 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 l(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 h=Symbol.for("wcstack.trustedTypes.policy"),u=Symbol.for("wcstack.trustedTypes.internal"),d="wcstack";function m(){const t=globalThis[h];return null===t||"object"!=typeof t?null:t}let p=!1;function g(t){const e=function(){const t=globalThis,e=t[u];if(void 0!==e)return e;const a=globalThis.trustedTypes;let n=null;if(a&&"function"==typeof a.createPolicy)try{n=a.createPolicy(d,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof m()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${d}". Allow it in the CSP (\`trusted-types ${d};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[u]=n,n}(),a=e?.createHTML;if("function"==typeof a)return a.call(e,t);if(!("trustedTypes"in globalThis))return t;const n=m(),s=n?.createHTML;return"function"==typeof s?(p||(p=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${d}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${d};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(n,t)):t}const f=new Map;class _ 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 f.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)f.has(e)?n.innerHTML=g(f.get(e)||""):n.innerHTML=g(await this._loadTemplateFromSource(e)||"");else if(a){const e=this._loadTemplateFromDocument(a);e?n.innerHTML=g(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 b 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 y=new Set(["props","states","attr",""]);function w(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 N(t,e){t.hasAttribute("data-bind")||a(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";y.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&&w(t,e,s)}).catch(()=>{a(`Failed to define custom element: ${i}`)}):w(t,e,s)}class v 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=>{N(e,t)}),e.hasAttribute("data-bind")&&N(e,t))}}function C(){return document.createElement(t.tagNames.layoutOutlet)}const P="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";async function E(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 c=t=>{t.effectiveDirective.startsWith("script-src")&&(l=!0)};document.addEventListener("securitypolicyviolation",c);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 ${P}`:`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 ${P}`}(t,s,l),{cause:s??t})}}}finally{document.removeEventListener("securitypolicyviolation",c)}return n&&"function"==typeof n.default?n.default:null}function k(t,e){E(t,e).then(t=>{t?e.guardHandler=t:e.notifyGuardHandlerLoadFailed()}).catch(t=>{console.error("loadGuardHandler failed:",t),e.notifyGuardHandlerLoadFailed()})}function A(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 S(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 c=l.tagName.toLowerCase();if(c===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),A(s,r),n.push(r),o=r.placeHolder,l=r}else{if(c===t.tagNames.guardHandler){if(n.length>0){const t=n[n.length-1],e=l.querySelector('script[type="module"]');e&&k(e,t)}continue}if("template"===c){r.appendChild(l);continue}if(c===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=C();n.layout=a,o=n,l=e}}const h=await S(e,l,n,s);l.replaceChildren(),l.appendChild(h),r.appendChild(o)}else r.appendChild(a);return r}async function $(t){const e=new Map;return await S(t,t.template.content,[],e)}function x(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(R(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(R(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 R(t){return!1!==t.checkVisibility?.()}function T(t,e,a,n){const i=function(t,e,a){const n={},i={};let r=!0,o=!1,l=0,c=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 h=a[c];if(void 0===h){r=!1;break}let u=!1;if("param"===e.type){const t=e.paramType||"any",a=s[t].parse(h);void 0!==a&&(e.paramName&&(n[e.paramName]=h,i[e.paramName]=a),u=!0)}else u=null!==e.pattern.exec(h);if(!u){r=!1;break}if("catch-all"===e.type){const t=a.slice(c).join("/");n["*"]=t,i["*"]=t,o=!0;break}l++,c++}let h=!1;return r&&(o||l===t.absoluteSegmentInfos.length&&c===a.length)&&(h=!0),h?{path:e,routes:t.routes,params:n,typedParams:i,lastPath:""}:null}(t,e,a);i&&n.push(i);for(const s of t.routeChildNodes)T(s,e,a,n)}function L(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)T(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 H=null,z=null;function I(){const e=t.basenameFileExtensions;return 0===e.length?null:(H===e&&z||(H=e,z=new RegExp(`\\/[^/]+(?:${e.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),z)}function O(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const a=I();return a&&(e=e.replace(a,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function M(t,e){let a=t;return""!==e&&(t===e?a="":t.startsWith(e+"/")&&(a=t.slice(e.length))),""===a?"/":a}function F(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const a=I();return a&&(e=e.replace(a,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function U(t){t.clearParams();for(const e of t.childNodeArray)e.parentNode?.removeChild(e)}function W(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=>{N(t,e.typedParams)}),n.hasAttribute("data-bind")&&N(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 j(t,e){W(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 D=Symbol.for("wcstack.transition-runner");function G(t,e,a){const n=function(t){const e=globalThis[D];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 B=Symbol.for("wcstack.binder");function q(){const t=globalThis[B];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const K=Symbol.for("wcstack.binder.pending"),V=Symbol.for("wcstack.binder.taken");function Y(){const t=globalThis;let e=t[V];return void 0===e&&(e=new WeakSet,t[V]=e),e}function J(t){const e=q();return null===e?(function(){const t=globalThis;let e=t[K];return void 0===e&&(e=[],t[K]=e),e}().push(t),!1):(Y().add(t),e.bind(t),!0)}const Q=new WeakSet,X="data-wcs";function Z(t,e,a){!Q.has(t)&&function(t){return t.hasAttribute(X)||null!==t.querySelector(`[${X}]`)}(t)&&(Q.add(t),function(t){if("complete"!==document.readyState)return void window.addEventListener("load",t,{once:!0});t()}(()=>{var n;null!==q()||(n=t,Y().has(n))||console.warn(`[@wcstack/router] ${e} contains ${X} 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 tt(t){for(const e of t.childNodeArray)1===e.nodeType&&(J(e)||Z(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 et(t,e){try{let t=null;for(const a of e.routes){const n=await a.guardCheck(e);n&&(t=null===t?n:Object.assign({},t,n))}e.data=t}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 at(e,n,s,i,r=""){const o=M(s,e.basename);if(e.isSameMatch(o))return e.commitNavigation({params:e.params,typedParams:e.typedParams,routeName:e.routeName,data:e.data,search:r,path:o}),!0;let l=L(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,l.search=r;const c=n.lastRoutes,h=await async function(t,e,a){if(!await et(t,e))return!1;const n=new Set(e.routes),s=new Set(a),i=()=>{for(const t of a)n.has(t)||U(t);let t=!1;for(const n of e.routes)(!s.has(n)||n.shouldChange(e.params)||t)&&(t=j(n,e),a.length>0&&!s.has(n)&&tt(n))};let r;return 0===a.length?i():r=G("router",i),void 0!==r&&await r,!0}(e,l,c);return!!h&&(e.commitNavigation({params:l.params,typedParams:l.typedParams,routeName:l.routes[l.routes.length-1]?.name??"",data:l.data??null,search:r,path:o}),n.lastRoutes=l.routes,c.length>0&&x(e,l),!0)}function nt(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function st(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 it(t){return"?"===t?"":t}function rt(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 ot(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const lt="data-wcs-ssr",ct="data-wcs-ssr-link",ht="@@wcs-route-ph:",ut="@@wcs-route-start:",dt="@@wcs-route-end:",mt=Object.freeze({});class pt 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"},{name:"data",event:"wcs-router:data-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=mt;_typedParams=mt;_searchParams=mt;_routeName="";_data=null;_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 O(t)}_normalizeBasename(t){return F(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}get data(){return this._data}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t){const e=Object.freeze({...t.params}),a=Object.freeze({...t.typedParams}),n=i(t.search),s=t.data??null,o=this._data!==s,l=!r(this._params,e),c=this._routeName!==t.routeName,h=!r(this._searchParams,n),u=this._path!==t.path;o&&(this._data=s),l&&(this._params=e,this._typedParams=a),c&&(this._routeName=t.routeName),h&&(this._searchParams=n),this._path=t.path,this._hasCommitted=!0,o&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),l&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),c&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),h&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),u&&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=st(t),n=""!==a.pathname||""===a.search&&""===a.hash?this._joinInternalPath(this._basename,a.pathname):window.location.pathname,s=n+it(a.search)+a.hash,i=nt();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(M(t,this._basename));await at(this,this.outlet,t,this._path,it(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(M(n,this._basename)),i=s&&("push"===e.navigationType||"replace"===e.navigationType),r=a.search,o=this;e.intercept({handler:async()=>{try{await at(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 at(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const e=ot();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 $(this),o=!e&&this._outlet.hasAttribute(lt);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(lt);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(r)}await at(this,this.outlet,l,this._path,window.location.search||""),(o||null!==q())&&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 c=0;for(;l.nextNode();){const t=l.currentNode,e=t.data;if(c++,e.startsWith(ht)){const a=e.slice(15);if(i.has(a)||!n.has(a))return!1;i.set(a,t)}else if(e.startsWith(ut)){const a=e.slice(18);if(r.has(a)||!n.has(a))return!1;r.set(a,{comment:t,index:c})}else if(e.startsWith(dt)){const a=e.slice(16);if(o.has(a)||!n.has(a))return!1;o.set(a,{comment:t,index:c})}}if(r.size!==o.size)return!1;const h=[];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;h.push({start:e.index,end:a.index})}for(const t of h)for(const e of h)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const u=M(e,this._basename);let d=L(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(ut)){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(lt);for(const t of d.routes)W(t,d);return this.outlet.lastRoutes=d.routes,!await et(this,d)||(this.commitNavigation({params:d.params,typedParams:d.typedParams,routeName:d.routes[d.routes.length-1].name,data:d.data??null,search:window.location.search||"",path:u}),!0)}async _renderForSsr(e){const n=M(e,this._basename),s=L(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 at(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${ht}${t.absolutePath}`}),this.outlet.setAttribute(lt,"");for(const t of this.outlet.lastRoutes){const e=t.placeHolder.parentNode,a=t.childNodeArray,n=document.createComment(`${ut}${t.absolutePath}`),s=document.createComment(`${dt}${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&&J(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(!rt(t,a))continue;const n=t,s=n[a];delete n[a],n[a]=s}}(this),ot()){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=nt();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&&(nt()?.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 gt=["title","rel","target","download","hreflang","lang","dir"];class ft extends HTMLElement{static get observedAttributes(){return["to",...gt]}_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 O(t)}_joinInternalPath(t,e){const a=F(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}=st(n),i=""===t?window.location.pathname:this._joinInternalPath(this.router.basename,t);e.href=i+it(a)+s}else try{e.href=new URL(n).toString()}catch{a(`[${t.tagNames.link}] Invalid URL in 'to' attribute: ${n}`)}}connectedCallback(){ot()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(ct)?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(ct),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-")||gt.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,ot())return this._updateActiveState(),void a.setAttribute(ct,"");nt()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!nt()?.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(){nt()?.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(gt.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}=st(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 _t=[],bt=new Map;let yt=!1;const wt=new WeakMap;class Nt 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(),yt||(this._captureInitialHead(),yt=!0),_t.push(this),this._reapplyHead()}disconnectedCallback(){const t=_t.indexOf(this);-1!==t&&_t.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||a("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=wt.get(t);if(void 0!==e)return e;const a=this._computeKey(t);return wt.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);bt.has(t)||bt.set(t,e.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of _t)for(const a of t._childElementArray)e.add(this._getKey(a));for(const t of bt.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=_t.length-1;t>=0;t--){const a=_t[t];for(const t of a._childElementArray)if(this._getKey(t)===n){e=t.cloneNode(!0);break}if(e)break}if(!e&&bt.has(n)){e=bt.get(n).cloneNode(!0)}const s=a.get(n)??null;e?(s?s.replaceWith(e):document.head.appendChild(e),a.set(n,e),J(e)||Z(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 vt(e=customElements){e.get(t.tagNames.layout)||e.define(t.tagNames.layout,_),e.get(t.tagNames.layoutOutlet)||e.define(t.tagNames.layoutOutlet,v),e.get(t.tagNames.outlet)||e.define(t.tagNames.outlet,b),e.get(t.tagNames.route)||e.define(t.tagNames.route,c),e.get(t.tagNames.router)||e.define(t.tagNames.router,pt),e.get(t.tagNames.link)||e.define(t.tagNames.link,ft),e.get(t.tagNames.head)||e.define(t.tagNames.head,Nt)}var Ct;await void vt(Ct);
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"]},e=t;function a(){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 n(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}class s extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}}const i={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}}};function r(t){const e={};for(const[a,n]of new URLSearchParams(t))e[a]=n;return Object.freeze(e)}function o(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}const l={static:2,param:1,"catch-all":0};class c 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(t,a){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&n(`${e.tagNames.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&n(`${e.tagNames.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?t(this._parentCore):a()}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+=l[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(i).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||n(`${e.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,n=await this._guardHandler(e,a,function(t){return Object.freeze({params:Object.freeze({...t.params}),typedParams:Object.freeze({...t.typedParams}),searchParams:r(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof n&&""!==n)throw new s("Navigation cancelled by guard.",n);if(!n)throw new s("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof n?n:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new s("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}}const h="data-wcs-ssr",u="data-wcs-ssr-link",d="@@wcs-route-ph:",m="@@wcs-route-start:",p="@@wcs-route-end:";class g extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=a();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new c(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||n(`${e.tagNames.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get endMarker(){return void 0===this._endMarker&&(this._endMarker=document.createComment(`${p}${this.absolutePath}`)),this._endMarker}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t,e){for(this._childNodeArray=[...t],e&&(this._endMarker=e);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(t,a){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):n(`${e.tagNames.route} should have a "path" or "index" attribute.`),this._routerNode=t,this._routeParentNode=a;const o=a||t;o.routeChildNodes.push(this),this._childIndex=o.routeChildNodes.length-1,r&&(a&&n(`${e.tagNames.route} with fallback attribute must be a direct child of ${e.tagNames.router}.`),t.fallbackRoute&&n(`${e.tagNames.router} can have only one fallback route.`),t.fallbackRoute=this),a&&(this._core.parentCore=a._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 f=Symbol.for("wcstack.trustedTypes.policy"),_=Symbol.for("wcstack.trustedTypes.internal"),b="wcstack";function y(){const t=globalThis[f];return null===t||"object"!=typeof t?null:t}let w=!1;function N(t){const e=function(){const t=globalThis,e=t[_];if(void 0!==e)return e;const a=globalThis.trustedTypes;let n=null;if(a&&"function"==typeof a.createPolicy)try{n=a.createPolicy(b,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof y()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${b}". Allow it in the CSP (\`trusted-types ${b};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[_]=n,n}(),a=e?.createHTML;if("function"==typeof a)return a.call(e,t);if(!("trustedTypes"in globalThis))return t;const n=y(),s=n?.createHTML;return"function"==typeof s?(w||(w=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${b}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${b};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(n,t)):t}const v=new Map;class C extends HTMLElement{_uuid=a();constructor(){super()}async _loadTemplateFromSource(t){try{const a=await fetch(t);a.ok||n(`${e.tagNames.layout} failed to fetch layout from source: ${t}, status: ${a.status}`);const s=await a.text();return v.set(t,s),s}catch(a){n(`${e.tagNames.layout} failed to load layout from source: ${t}, error: ${a}`,{cause:a})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const t=this.getAttribute("src"),a=this.getAttribute("layout");t&&a&&console.warn(`${e.tagNames.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)v.has(t)?n.innerHTML=N(v.get(t)||""):n.innerHTML=N(await this._loadTemplateFromSource(t)||"");else if(a){const t=this._loadTemplateFromDocument(a);t?n.innerHTML=N(t):console.warn(`${e.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")&&e.enableShadowRoot}get name(){return this.getAttribute("name")||""}}class P extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||n(`${e.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")&&e.enableShadowRoot}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const k=new Set(["props","states","attr",""]);function E(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 A(t,e){t.hasAttribute("data-bind")||n(`${t.tagName} has no 'data-bind' attribute.`);const a=t.getAttribute("data-bind")||"";k.has(a)||n(`${t.tagName} has invalid 'data-bind' attribute: ${a}`);const s=a,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&&E(t,e,s)}).catch(()=>{n(`Failed to define custom element: ${i}`)}):E(t,e,s)}const S=Symbol.for("wcstack.binder");function $(){const t=globalThis[S];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const x=Symbol.for("wcstack.binder.pending"),R=Symbol.for("wcstack.binder.taken");function T(){const t=globalThis;let e=t[R];return void 0===e&&(e=new WeakSet,t[R]=e),e}function L(t,e){const a=$();return null===a?(function(){const t=globalThis;let e=t[x];return void 0===e&&(e=[],t[x]=e),e}().push(t),!1):(T().add(t),a.bind(t,e),!0)}const H={range:!0};function z(t,e){for(const a of t.routeChildNodes)e.add(a.placeHolder).add(a.endMarker),z(a,e);return e}function I(t){const e=t.placeHolder,a=t.endMarker,n=null!==a.parentNode&&a.parentNode===e.parentNode&&!!(4&e.compareDocumentPosition(a)),s=n?null:z(t,new Set),i=[];let r=0;for(let o=e.nextSibling;null!==o&&o!==a&&(null===s||8!==o.nodeType||!/^@@(route:|wcs-route-)/.test(o.data)||s.has(o));o=o.nextSibling)i.push(o),(n||t.childNodeArray.includes(o))&&(r=i.length);return i.length=r,i}class M extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||n(`${e.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 t=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(t.content.cloneNode(!0));for(const t of Array.from(this.layout.childNodes))this._layoutChildNodes.push(t),this.appendChild(t)}else{const a=t.content.cloneNode(!0),n=new Map;a.querySelectorAll("slot").forEach(t=>{const a=t.getAttribute("name")||"";n.has(a)?console.warn(`${e.tagNames.layoutOutlet} duplicate slot name "${a}" in layout template.`):n.set(a,t)});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)}!function(t){if(null!==$())for(const e of t)1===e.nodeType&&L(e,H)}(Array.from(this.childNodes))}finally{this._initializing=!1}}async connectedCallback(){this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected)}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{A(e,t)}),e.hasAttribute("data-bind")&&A(e,t))}}function O(){return document.createElement(e.tagNames.layoutOutlet)}const F="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";async function U(t,e){let a=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 c=t=>{t.effectiveDirective.startsWith("script-src")&&(l=!0)};document.addEventListener("securitypolicyviolation",c);try{if("function"==typeof URL.createObjectURL){const t=new Blob([o],{type:"application/javascript"}),e=URL.createObjectURL(t);try{a=await import(e)}catch(t){s=t}finally{URL.revokeObjectURL(e)}}if(!a){const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(o)));try{a=await import(`data:application/javascript;base64,${t}`)}catch(t){await new Promise(t=>setTimeout(t)),n(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: give the page's nonce to the <script> that loads @wcstack/router, or allow blob: in script-src. See ${F}`:`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 ${F}`}(t,s,l),{cause:s??t})}}}finally{document.removeEventListener("securitypolicyviolation",c)}return a&&"function"==typeof a.default?a.default:null}function W(t,e){U(t,e).then(t=>{t?e.guardHandler=t:e.notifyGuardHandlerLoadFailed()}).catch(t=>{console.error("loadGuardHandler failed:",t),e.notifyGuardHandlerLoadFailed()})}function j(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 D(t,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 c=l.tagName.toLowerCase();if(c===e.tagNames.route){const e=document.createDocumentFragment();for(const t of Array.from(l.childNodes))e.appendChild(t);const a=document.importNode(l,!0);customElements.upgrade(a),a.appendChild(e);const r=a;r.initialize(t,i),j(s,r),n.push(r),o=r.placeHolder,l=r}else{if(c===e.tagNames.guardHandler){if(n.length>0){const t=n[n.length-1],e=l.querySelector('script[type="module"]');e&&W(e,t)}continue}if("template"===c){r.appendChild(l);continue}if(c===e.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=O();n.layout=a,o=n,l=e}}const h=await D(t,l,n,s);l.replaceChildren(),l.appendChild(h),r.appendChild(o)}else r.appendChild(a);return r}async function G(t){const e=new Map;return await D(t,t.template.content,[],e)}function q(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(B(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(B(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 B(t){return!1!==t.checkVisibility?.()}function K(t,e,a,n){const s=function(t,e,a){const n={},s={};let r=!0,o=!1,l=0,c=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 h=a[c];if(void 0===h){r=!1;break}let u=!1;if("param"===e.type){const t=e.paramType||"any",a=i[t].parse(h);void 0!==a&&(e.paramName&&(n[e.paramName]=h,s[e.paramName]=a),u=!0)}else u=null!==e.pattern.exec(h);if(!u){r=!1;break}if("catch-all"===e.type){const t=a.slice(c).join("/");n["*"]=t,s["*"]=t,o=!0;break}l++,c++}let h=!1;return r&&(o||l===t.absoluteSegmentInfos.length&&c===a.length)&&(h=!0),h?{path:e,routes:t.routes,params:n,typedParams:s,lastPath:""}:null}(t,e,a);s&&n.push(s);for(const s of t.routeChildNodes)K(s,e,a,n)}function V(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)K(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 Y=null,J=null;function Q(){const t=e.basenameFileExtensions;return 0===t.length?null:(Y===t&&J||(Y=t,J=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),J)}function X(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const a=Q();return a&&(e=e.replace(a,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function Z(t,e){let a=t;return""!==e&&(t===e?a="":t.startsWith(e+"/")&&(a=t.slice(e.length))),""===a?"/":a}function tt(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const a=Q();return a&&(e=e.replace(a,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function et(t){if(null!==t.held)return;const e=I(t),a=new Set(e),n=[...e,...t.childNodeArray];let s=null;for(const i of t.childNodeArray)a.has(i)?s=i:null===i.parentNode||n.some(t=>t!==i&&t.contains(i))||(e.splice(null===s?0:e.indexOf(s)+1,0,i),a.add(i),s=i);const i=document.createDocumentFragment();!function(t,e){const a=e.map(t=>t.parentNode);for(let n=0;n<e.length;n++)e[n].parentNode===a[n]&&t.appendChild(e[n])}(i,e),i.appendChild(t.endMarker),t.held=i}function at(t){t.clearParams(),et(t)}function nt(t,a){const n={},s={};for(const e of t.paramNames)n[e]=a.params[e],s[e]=a.typedParams[e];t.setParams(n,s);for(const a of t.childNodeArray)if(a.nodeType===Node.ELEMENT_NODE){const n=a;n.querySelectorAll("[data-bind]").forEach(e=>{A(e,t.typedParams)}),n.hasAttribute("data-bind")&&A(n,t.typedParams),n.querySelectorAll(e.tagNames.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===e.tagNames.layoutOutlet&&n.assignParams(t.typedParams)}}const st=new WeakSet;function it(t){const e=t.placeHolder;null!==e.parentNode&&(st.has(t)||null!==t.endMarker.parentNode?(et(t),e.after(t.held),t.held=null):e.after(...t.childNodeArray,t.endMarker),st.add(t))}const rt=Symbol.for("wcstack.transition-runner");function ot(t,e,a){const n=function(t){const e=globalThis[rt];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 lt=new WeakSet,ct="data-wcs";function ht(t,e,a){!lt.has(t)&&function(t){return t.hasAttribute(ct)||null!==t.querySelector(`[${ct}]`)}(t)&&(lt.add(t),function(t){if("complete"!==document.readyState)return void window.addEventListener("load",t,{once:!0});t()}(()=>{var n;null!==$()||(n=t,T().has(n))||console.warn(`[@wcstack/router] ${e} contains ${ct} 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 ut(t){for(const e of t.childNodeArray)if(1===e.nodeType){if(e.isConnected){if(L(e,H))continue}else if(null!==$())continue;ht(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 dt(t,e){try{let t=null;for(const a of e.routes){const n=await a.guardCheck(e);n&&(t=null===t?n:Object.assign({},t,n))}e.data=t}catch(e){if(e instanceof s)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 mt(t,a,s,i,r=""){const o=Z(s,t.basename);if(t.isSameMatch(o))return t.commitNavigation({params:t.params,typedParams:t.typedParams,routeName:t.routeName,data:t.data,search:r,path:o}),!0;let l=V(t,o);l||(t.fallbackRoute?l={routes:[t.fallbackRoute],params:{},typedParams:{},path:o,lastPath:i}:n(`${e.tagNames.router} No route matched for path: ${o}`)),l.lastPath=i,l.search=r;const c=a.lastRoutes,h=await async function(t,e,a){if(!await dt(t,e))return!1;const n=new Set(e.routes),s=new Set(a),i=()=>{for(const t of a)n.has(t)||at(t);const t=[];for(const a of e.routes)(t.length>0||!s.has(a)||a.shouldChange(e.params))&&(t.push(a),nt(a,e));let i=!1;for(const e of t){const t=s.has(e);t&&i||it(e),i||=t,a.length>0&&!t&&ut(e)}};let r;return 0===a.length?i():r=ot("router",i),void 0!==r&&await r,!0}(t,l,c);return!!h&&(t.commitNavigation({params:l.params,typedParams:l.typedParams,routeName:l.routes[l.routes.length-1]?.name??"",data:l.data??null,search:r,path:o}),a.lastRoutes=l.routes,c.length>0&&q(t,l),!0)}function pt(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function gt(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 ft(t){return"?"===t?"":t}function _t(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 bt(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const yt=Object.freeze({});class wt 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"},{name:"data",event:"wcs-router:data-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=yt;_typedParams=yt;_searchParams=yt;_routeName="";_data=null;_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 X(t)}_normalizeBasename(t){return tt(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 t=this.nextElementSibling;if(t&&t.matches(e.tagNames.outlet))return t;const a=document.createElement(e.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||n(`${e.tagNames.router} has no outlet.`),this._outlet}get template(){return this._template||n(`${e.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}get data(){return this._data}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t){const e=Object.freeze({...t.params}),a=Object.freeze({...t.typedParams}),n=r(t.search),s=t.data??null,i=this._data!==s,l=!o(this._params,e),c=this._routeName!==t.routeName,h=!o(this._searchParams,n),u=this._path!==t.path;i&&(this._data=s),l&&(this._params=e,this._typedParams=a),c&&(this._routeName=t.routeName),h&&(this._searchParams=n),this._path=t.path,this._hasCommitted=!0,i&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),l&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),c&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),h&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),u&&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(t){null!=t&&""!==t&&this._navigateUrl!==t&&(this._navigateUrl=t,this.navigate(t).catch(t=>{console.error(`${e.tagNames.router} navigate failed:`,t)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(t){null!=t&&""!==t&&this._replaceUrl!==t&&(this._replaceUrl=t,this.replace(t).catch(t=>{console.error(`${e.tagNames.router} replace failed:`,t)}).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=gt(t),n=""!==a.pathname||""===a.search&&""===a.hash?this._joinInternalPath(this._basename,a.pathname):window.location.pathname,s=n+ft(a.search)+a.hash,i=pt();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(Z(t,this._basename));await mt(this,this.outlet,t,this._path,ft(a.search))&&!i&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||(t===this._basename||t.startsWith(this._basename+"/"))}_onNavigateFunc(t){if(!t.canIntercept||t.hashChange||null!==t.downloadRequest)return;const a=new URL(t.destination.url),n=this._normalizePathname(a.pathname);if(!this._isOwnPath(n))return;const s=this.isSameMatch(Z(n,this._basename)),i=s&&("push"===t.navigationType||"replace"===t.navigationType),r=a.search,o=this;t.intercept({handler:async()=>{try{await mt(o,o.outlet,n,o.path,r)}catch(t){throw console.error(`${e.tagNames.router} applyRoute failed:`,t),t}},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 mt(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=bt();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const a=null!==document.querySelector("base[href]"),s=new URL(window.location.href);""!==this._basename||a||"/"===s.pathname||n(`${e.tagNames.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||n(`${e.tagNames.router} should have a <template> child element.`);const i=t?this._template.content.cloneNode(!0):null,r=await G(this),o=!t&&this._outlet.hasAttribute(h);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&&n(`${e.tagNames.router} has no route definitions.`),t||this._ensureA11yRegion();const l=this._normalizePathname(window.location.pathname);if(t)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(h);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(r)}await mt(this,this.outlet,l,this._path,window.location.search||""),(o||null!==$())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(t){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(e.tagNames.layoutOutlet))return!1;const i=new Map,r=new Map,o=new Map,l=document.createTreeWalker(a,NodeFilter.SHOW_COMMENT);let c=0;for(;l.nextNode();){const t=l.currentNode,e=t.data;if(c++,e.startsWith(d)){const a=e.slice(15);if(i.has(a)||!n.has(a))return!1;i.set(a,t)}else if(e.startsWith(m)){const a=e.slice(18);if(r.has(a)||!n.has(a))return!1;r.set(a,{comment:t,index:c})}else if(e.startsWith(p)){const a=e.slice(16);if(o.has(a)||!n.has(a))return!1;o.set(a,{comment:t,index:c})}}if(r.size!==o.size)return!1;const u=[];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;u.push({start:e.index,end:a.index})}for(const t of u)for(const e of u)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const g=Z(t,this._basename);let f=V(this,g);if(!f){if(null===this._fallbackRoute)return!1;f={routes:[this._fallbackRoute],params:{},typedParams:{},path:g,lastPath:this._path}}if(f.lastPath=this._path,f.routes.length!==r.size)return!1;for(const t of f.routes)if(!r.has(t.absolutePath))return!1;const _=new Set;for(const t of this.routeChildNodes)_.add(t.absolutePath);for(const t of f.routes)for(const e of t.routeChildNodes)_.add(e.absolutePath);if(i.size!==_.size)return!1;for(const t of _)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 t of f.routes){const a=r.get(t.absolutePath).comment,n=o.get(t.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(m)){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()===e.tagNames.link){const t=l.anchorElement;null!==t&&i.add(t)}s.push(l),l=l.nextSibling}}t.adoptChildNodes(s,n)}for(const{comment:t}of r.values())t.remove();this.outlet.removeAttribute(h);for(const t of f.routes)nt(t,f);return this.outlet.lastRoutes=f.routes,!await dt(this,f)||(this.commitNavigation({params:f.params,typedParams:f.typedParams,routeName:f.routes[f.routes.length-1].name,data:f.data??null,search:window.location.search||"",path:g}),!0)}async _renderForSsr(t){const a=Z(t,this._basename),s=V(this,a),i=s?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===i.length&&n(`${e.tagNames.router} No route matched for path: ${a}`),!i.some(t=>t.hasGuard)){await mt(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${d}${t.absolutePath}`}),this.outlet.setAttribute(h,"");for(const t of this.outlet.lastRoutes)t.placeHolder.after(document.createComment(`${m}${t.absolutePath}`))}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&e.isConnected&&L(e,H)}_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(!_t(t,a))continue;const n=t,s=n[a];delete n[a],n[a]=s}}(this),bt()){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=pt();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&&(pt()?.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 Nt=["title","rel","target","download","hreflang","lang","dir"];class vt extends HTMLElement{static get observedAttributes(){return["to",...Nt]}_childNodeArray=[];_uuid=a();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const t=this.closest(e.tagNames.router);if(t)return this._router=t;const a=this.getRootNode(),s=a.querySelector?.(e.tagNames.router);if(s)return this._router=s;n(`${e.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 X(t)}_joinInternalPath(t,e){const a=tt(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(t,a){if(this._isInternalTarget(a)){const{pathname:e,search:n,hash:s}=gt(a),i=""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e);t.href=i+ft(n)+s}else try{t.href=new URL(a).toString()}catch{n(`[${e.tagNames.link}] Invalid URL in 'to' attribute: ${a}`)}}connectedCallback(){bt()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(u)?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(u),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-")||Nt.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,bt())return this._updateActiveState(),void a.setAttribute(u,"");pt()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!pt()?.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(){pt()?.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(Nt.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}=gt(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=[],Pt=new Map;let kt=!1;const Et=new WeakMap;class At 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(),kt||(this._captureInitialHead(),kt=!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||n("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=Et.get(t);if(void 0!==e)return e;const a=this._computeKey(t);return Et.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);Pt.has(t)||Pt.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of Ct)for(const a of e._childElementArray)t.add(this._getKey(a));for(const e of Pt.keys())t.add(e);const a=this._buildHeadElementMap();for(const e of a.keys())t.add(e);for(const n of t){let t=null;for(let e=Ct.length-1;e>=0;e--){const a=Ct[e];for(const e of a._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}if(!t&&Pt.has(n)){t=Pt.get(n).cloneNode(!0)}const s=a.get(n)??null;t?(s?s.replaceWith(t):document.head.appendChild(t),a.set(n,t),L(t)||ht(t,`<${t.tagName.toLowerCase()}> inside <${e.tagNames.head}>`,`<${e.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 St(t=customElements){t.get(e.tagNames.layout)||t.define(e.tagNames.layout,C),t.get(e.tagNames.layoutOutlet)||t.define(e.tagNames.layoutOutlet,M),t.get(e.tagNames.outlet)||t.define(e.tagNames.outlet,P),t.get(e.tagNames.route)||t.define(e.tagNames.route,g),t.get(e.tagNames.router)||t.define(e.tagNames.router,wt),t.get(e.tagNames.link)||t.define(e.tagNames.link,vt),t.get(e.tagNames.head)||t.define(e.tagNames.head,At)}var $t;await void St($t);
2
2
  //# sourceMappingURL=auto.min.js.map