@wcstack/router 4.0.4 → 4.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +10 -5
- package/README.md +10 -5
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/dist/index.d.ts +53 -5
- package/dist/index.esm.js +196 -40
- package/dist/index.esm.js.map +1 -1
- package/package.json +1 -1
package/README.ja.md
CHANGED
|
@@ -182,15 +182,16 @@ router は、スタンプしたルート本文の終わりにコメントの印
|
|
|
182
182
|
| `searchParams` | output のみ | 現在 URL のクエリ(`Record<string, string>`)。キー重複(`?tag=a&tag=b`)は **last-wins**、デコードは `URLSearchParams` に委ねる(`+` → 空白を含む)。クエリ無しは `{}`。`wcs-router:search-changed` を発火 |
|
|
183
183
|
| `routeName` | output のみ | 最深マッチルートの `name` 属性値。fallback マッチ時は fallback ルートの `name`(404 画面も `routeName` 分岐で書ける)。無名・初期化前は `""`。`wcs-router:route-name-changed` を発火 |
|
|
184
184
|
| `data` | output のみ | 現在のナビゲーションの guard 関数がロードしたデータ — `true` の代わりにオブジェクトを返した guard の返り値([ルート commit 前のデータロード](#ルート-commit-前のデータロード) 参照)。どの guard もオブジェクトを返さなければ `null`(初期化前も `null`)。クエリのみの遷移(same-match)では前の値を保つ。上の各メンバーと違い **frozen にしない** — guard が返したオブジェクトをそのまま露出する。`wcs-router:data-changed` を発火 |
|
|
185
|
-
| `navigateUrl` | 書き込み面(null-idle transient) | ターゲットを書くと push 遷移。null は待機、文字列の書き込みで `navigate()` が起動し、完了後に自分で null へ戻る。null / `""` の書き込みは no-op |
|
|
185
|
+
| `navigateUrl` | 書き込み面(null-idle transient) | ターゲットを書くと push 遷移。null は待機、文字列の書き込みで `navigate()` が起動し、完了後に自分で null へ戻る。null / `""` の書き込みは no-op。書くのは**ルートのパス** — basename は router が付ける: リンクの `href` ではなく `/products/3` を書く(basename `/ja` の下で `/ja/products/3` を書くと `/ja/ja/products/3` へ行く) |
|
|
186
186
|
| `replaceUrl` | 書き込み面(null-idle transient) | `navigateUrl` と完全同型の契約。ただし現在の履歴エントリを**置き換える** |
|
|
187
|
+
| `leaveConfirm` | input(属性 `leave-confirm`) | 空でない文字列の間、**別のルート**へのナビゲーション(リンク・戻る / 進む・`navigate()`)の前に `confirm(leaveConfirm)` を出し、断られたら留まる。ページを閉じる・読み直すときはブラウザ自身の確認(`beforeunload`)。未保存の変更に束ねる: `data-wcs="leaveConfirm: discardPrompt"` と `get discardPrompt() { return this.dirty ? "変更を破棄しますか?" : null; }`。クエリだけの遷移と、確認済みの遷移のリダイレクトでは聞かない。保存のハンドラが同じ更新でこれを外して `navigateUrl` を書いてもよい — router はその更新の後で確かめる。ブラウザがページに取り消させない戻る / 進むでは聞けない。`null` は属性を外す |
|
|
187
188
|
| `basename` | input | `basename` 属性に書く。Router はこの属性を初期化のときに一度だけ読むので、それより前に書く(後から書いてもルーティングの基準は変わらない。属性を書き換えたときと同じ)。読むと使われている basename を返す(初期化前は `""`)。`null` は属性を外し、`undefined` は最初の属性へ戻す |
|
|
188
189
|
|
|
189
190
|
コマンド `navigate(path)` / `replace(path)`(いずれも async)も宣言され、command-token プロトコルから起動できる。
|
|
190
191
|
|
|
191
192
|
output-only メンバーはバインド attach 時に**読まれ**、以後は変更イベントで流れる — 値は「読むもの」であり「待つもの」ではないので、router が最初のルートを解決した後に attach したバインドでも取りこぼしはない。
|
|
192
193
|
|
|
193
|
-
**発火規範**: commit されたナビゲーションでは、router はまず**全内部値をコミット**し、その後で `data-changed` → `params-changed` → `route-name-changed` → `search-changed` → `path-changed` の順に、値が実際に変化したものだけを発火する(`data` は同一性比較 — guard は遷移ごとに新しいオブジェクトを返す)。どのイベントのリスナーから要素プロパティを読んでも遷移後スナップショットの一貫した値が見える。`path`
|
|
194
|
+
**発火規範**: commit されたナビゲーションでは、router はまず**全内部値をコミット**し、その後で `data-changed` → `params-changed` → `route-name-changed` → `search-changed` → `path-changed` の順に、値が実際に変化したものだけを発火する(`data` は同一性比較 — guard は遷移ごとに新しいオブジェクトを返す)。どのイベントのリスナーから要素プロパティを読んでも遷移後スナップショットの一貫した値が見える。`path` は最後に発火し「ナビゲーション完了」の信号を兼ねる。前の 4 つはルートの中身を置く**前**に、`path` は置いた後に発火する。だから新しい中身のバインディングは、最初の評価から新しい params と data を読む。guard 拒否されたナビゲーションでは何も更新せず何も発火しない。
|
|
194
195
|
|
|
195
196
|
露出オブジェクトは router が所有する **frozen スナップショット**(ナビゲーションごとに新しいオブジェクト、in-place 変異なし)。変異は throw する — 自分の state へコピーして使うこと。唯一の例外が `data` — 所有者は返した guard であり、router はコピーも freeze もしない。
|
|
196
197
|
|
|
@@ -227,7 +228,7 @@ basename 結合と pathname 正規化は pathname にのみ適用され、クエ
|
|
|
227
228
|
| `fallback` | ルートパスに対応するルートがない場合、表示する |
|
|
228
229
|
| `fullpath` | 上位ルートを含むパス、読み取り専用 |
|
|
229
230
|
| `name` | 識別用 |
|
|
230
|
-
| `guard` |
|
|
231
|
+
| `guard` | ガード関数が falsy を返したときのリダイレクト先の絶対パス(既定は `/`)。`<wcs-guard-handler>` を持つルートは、この属性が無くてもガードを持つ。JS からハンドラを設定する(`guardHandler`)ルートは、この属性でガードを有効にする |
|
|
231
232
|
|
|
232
233
|
| プロパティ | 説明 |
|
|
233
234
|
|------|------|
|
|
@@ -274,8 +275,11 @@ interface IGuardContext { // 進入先マッチの frozen スナップ
|
|
|
274
275
|
</wcs-route>
|
|
275
276
|
```
|
|
276
277
|
|
|
277
|
-
-
|
|
278
|
-
- 判定関数が `false` を返すとナビゲーションがキャンセルされ、`guard` 属性のパスへ遷移。空でない文字列を返すとそのパスへ遷移(例: `` return `/login?next=${encodeURIComponent(toPath)}`
|
|
278
|
+
- ハンドラがあればそれだけでガードが有効になり、そのルートへのナビゲーションはどれも(最初の 1 回も)ハンドラを待つ。`guard` 属性は falsy を返したときのリダイレクト先(既定は `/`)
|
|
279
|
+
- 判定関数が `false` を返すとナビゲーションがキャンセルされ、`guard` 属性のパスへ遷移。空でない文字列を返すとそのパスへ遷移(例: `` return `/login?next=${encodeURIComponent(toPath)}` ``)。`toPath` にクエリは含まれない。リダイレクト先に要るなら第 3 引数の `searchParams` から組み直す(`new URLSearchParams(searchParams)`)
|
|
280
|
+
- リダイレクトは、キャンセルしたナビゲーションの履歴エントリを**置き換える**。だから「戻る」で守られた URL へ戻る(そしてすぐまたリダイレクトされる)ことはない。リダイレクトはガードの本来の使い方なので、コンソールには何も出さない。ガード同士が送り合うリダイレクトは、続けて 10 回で止め、最後の 1 回を名指すエラーを出す。リダイレクトされたナビゲーションの `navigate()` / `replace()` は `AbortError` で reject する
|
|
281
|
+
- モジュールは**一度だけ**評価され、関数はナビゲーションのたびに呼ばれる。変わるもの(セッション)は、モジュールの先頭ではなく関数の中で読む
|
|
282
|
+
- ガードから `<wcs-state>` の状態は見えない。ページの読み込みでは、最初のルートのガードが `@wcstack/state` の読み込みより先に走ることもある。セッションは、それを保存している場所 — `<wcs-storage>` が保存する `localStorage` のキー(JSON で入っている)— から直接読む。どのタブでも最新の値になる
|
|
279
283
|
- 判定関数は `Promise` を返すことも可能(非同期チェック対応)— 解決するまでルートは commit されない
|
|
280
284
|
- 第 3 引数に進入先マッチ(`params` / `typedParams` / `searchParams` / `routeName`)が渡る。`toPath` / `fromPath` は basename スライス後のパス
|
|
281
285
|
- `<wcs-route>` の外に配置された `<wcs-guard-handler>` は無視される
|
|
@@ -448,6 +452,7 @@ console.log(router.typedParams.userId); // 123 (number)
|
|
|
448
452
|
| 属性 | 説明 |
|
|
449
453
|
|------|------|
|
|
450
454
|
| `to` | 遷移先の絶対ルートパスもしくはURL。`/`で始まる場合はルートパス(basename は pathname にのみ付与され、`?クエリ` / `#ハッシュ` はそのまま温存される)。`?` で始まる場合は**クエリのみリンク**:href は「現在 pathname + 指定クエリ」で組み立てられ、ロケーション変更に追従する。それ以外は外部URLとして扱われる |
|
|
455
|
+
| `match` | `exact`(既定)か `prefix`。`prefix` なら下のパスでも active になる(サイドナビの「商品」が `/products/3` でも)。そのときの `aria-current` は `"true"`(そのパス自身では `"page"`) |
|
|
451
456
|
|
|
452
457
|
**アクティブ状態**: 生成された `<a>` はパスが現在のロケーションと一致する場合に `active` クラスと、同じ事実の ARIA 表現である `aria-current="page"` を受け取る(スクリーンリーダーがナビゲーション内の現在地を読み上げられる)。比較は **pathname のみ**で行われ、どちら側のクエリも影響しない(`to="/products"` は `/products?page=2` でも active のまま。クエリのみリンクはそのページに居る間つねに active)。ナビゲーションイベント(`currententrychange`, `wcs:navigate`, `popstate`)で更新される。
|
|
453
458
|
|
package/README.md
CHANGED
|
@@ -182,15 +182,16 @@ Define routes and layout slots inside a child template tag. A direct child templ
|
|
|
182
182
|
| `searchParams` | output only | Current URL query as `Record<string, string>`. Duplicate keys (`?tag=a&tag=b`) are **last-wins**; values are decoded by `URLSearchParams` (including `+` → space). `{}` when there is no query. Fires `wcs-router:search-changed`. |
|
|
183
183
|
| `routeName` | output only | `name` attribute of the deepest matched route. On a fallback match, the fallback route's `name` (so a 404 view can key off `routeName` too). `""` when unnamed or before initialization. Fires `wcs-router:route-name-changed`. |
|
|
184
184
|
| `data` | output only | Data the current navigation's guard functions loaded — a guard that returns an object instead of `true` (see [Loading data before a route commits](#loading-data-before-a-route-commits)). `null` when no guard returned data, including before initialization; a query-only (same-match) navigation keeps the previous value. Unlike the members above it is **not** frozen: it is the object your guard returned, passed through as-is. Fires `wcs-router:data-changed`. |
|
|
185
|
-
| `navigateUrl` | write surface (null-idle transient) | Write a target to push-navigate. `null` means idle; writing a string starts `navigate()`, and the property resets itself to `null` when the navigation finishes. `null` / `""` writes are no-ops. |
|
|
185
|
+
| `navigateUrl` | write surface (null-idle transient) | Write a target to push-navigate. `null` means idle; writing a string starts `navigate()`, and the property resets itself to `null` when the navigation finishes. `null` / `""` writes are no-ops. The target is a **route path** — the basename is added for you: write `/products/3`, not the `href` of a link (`/ja/products/3` under the basename `/ja` lands on `/ja/ja/products/3`). |
|
|
186
186
|
| `replaceUrl` | write surface (null-idle transient) | Identical contract to `navigateUrl`, but the navigation **replaces** the current history entry. |
|
|
187
|
+
| `leaveConfirm` | input (attribute `leave-confirm`) | While it is a non-empty string, a navigation to **another route** — a link, Back / Forward, `navigate()` — first asks `confirm(leaveConfirm)` and stays when it is declined; closing or reloading the page gets the browser's own prompt (`beforeunload`). Bind it to unsaved changes: `data-wcs="leaveConfirm: discardPrompt"` with `get discardPrompt() { return this.dirty ? "Discard your changes?" : null; }`. A query-only navigation does not ask, nor does the redirect of a navigation already confirmed. A save handler may clear it and write `navigateUrl` in the same update: the router checks after that update. A Back / Forward the browser does not let a page cancel is not asked. `null` removes the attribute. |
|
|
187
188
|
| `basename` | input | Writes the `basename` attribute, which the router reads once, when it initializes: set it before then (a later write does not move the routing base, as with the attribute). Reading it returns the basename in effect (`""` before initialization). `null` removes the attribute; `undefined` restores the attribute the element started with. |
|
|
188
189
|
|
|
189
190
|
Commands `navigate(path)` and `replace(path)` (both async) are also declared, so they can be invoked through the command-token protocol.
|
|
190
191
|
|
|
191
192
|
Output-only members are **read** when a binding attaches and streamed through their change events afterwards — the value is read, not awaited, so a binding that attaches after the router already resolved its first route misses nothing.
|
|
192
193
|
|
|
193
|
-
**Firing contract**: on a committed navigation the router commits *all* internal values first and only then fires events, in the order `data-changed` → `params-changed` → `route-name-changed` → `search-changed` → `path-changed`, each only when its value actually changed (`data` compares by identity — a guard returns a fresh object per navigation). Any listener that reads the element's properties sees the consistent post-navigation snapshot; `path` fires last and doubles as the "navigation finished" signal. A guard-rejected navigation updates nothing and fires nothing.
|
|
194
|
+
**Firing contract**: on a committed navigation the router commits *all* internal values first and only then fires events, in the order `data-changed` → `params-changed` → `route-name-changed` → `search-changed` → `path-changed`, each only when its value actually changed (`data` compares by identity — a guard returns a fresh object per navigation). Any listener that reads the element's properties sees the consistent post-navigation snapshot; `path` fires last and doubles as the "navigation finished" signal. The first four fire **before** the route's content is placed and `path` after it, so the bindings inside the new content read the new params and data from their first evaluation. A guard-rejected navigation updates nothing and fires nothing.
|
|
194
195
|
|
|
195
196
|
The exposed objects are **frozen snapshots** owned by the router: a new object per navigation, never mutated in place. Mutating them throws — copy into your own state instead. `data` is the one exception — it is owned by the guard that returned it, and the router neither copies nor freezes it.
|
|
196
197
|
|
|
@@ -227,7 +228,7 @@ Displays children when the route path matches. Match priority is static paths ov
|
|
|
227
228
|
| `fallback` | Displayed when no route matches the path. |
|
|
228
229
|
| `fullpath` | Path including parent routes (read-only). |
|
|
229
230
|
| `name` | Identifier. |
|
|
230
|
-
| `guard` |
|
|
231
|
+
| `guard` | The full path to redirect to when the guard handler returns a falsy value (default `/`). A route with a `<wcs-guard-handler>` has a guard without it; a route whose handler is set from JS (`guardHandler`) needs it to enable guard handling. |
|
|
231
232
|
|
|
232
233
|
| Property | Description |
|
|
233
234
|
|------|------|
|
|
@@ -274,8 +275,11 @@ Place as a child of `<wcs-route>` to declaratively define a guard decision funct
|
|
|
274
275
|
</wcs-route>
|
|
275
276
|
```
|
|
276
277
|
|
|
277
|
-
- The `guard` attribute
|
|
278
|
-
- If the function returns `false`, navigation is cancelled and the user is redirected to the `guard` path; a non-empty string redirects there instead (e.g. `` return `/login?next=${encodeURIComponent(toPath)}` ``)
|
|
278
|
+
- The handler enables guard handling by itself, and every navigation into the route waits for it — the first one included. The `guard` attribute is the redirect for a falsy result (default `/`)
|
|
279
|
+
- If the function returns `false`, navigation is cancelled and the user is redirected to the `guard` path; a non-empty string redirects there instead (e.g. `` return `/login?next=${encodeURIComponent(toPath)}` ``). `toPath` has no query string: rebuild it from the third argument's `searchParams` when the target needs it (`new URLSearchParams(searchParams)`)
|
|
280
|
+
- A redirect **replaces** the history entry of the cancelled navigation, so Back does not lead to the guarded URL (and straight back to the redirect). It is not logged — it is what the guard is for. Guards that keep redirecting each other are stopped after 10 redirects in a row, with an error naming the last one. A `navigate()` / `replace()` whose navigation is redirected rejects with an `AbortError`
|
|
281
|
+
- The module is evaluated **once**; the function runs on every navigation. Read anything that changes — a session — inside the function, not at the module's top level
|
|
282
|
+
- A guard does not see the `<wcs-state>` tree, and on a page load the landing route's guard can run before `@wcstack/state` has loaded. Read what the session is kept in directly — `localStorage`, under the key a `<wcs-storage>` saves it to (stored as JSON) — which is also current in every tab
|
|
279
283
|
- The function can return a `Promise` for async checks — the route is not committed until it settles
|
|
280
284
|
- The third argument carries the match being entered (`params` / `typedParams` / `searchParams` / `routeName`); `toPath` / `fromPath` are basename-sliced paths
|
|
281
285
|
- `<wcs-guard-handler>` placed outside a `<wcs-route>` is ignored
|
|
@@ -448,6 +452,7 @@ Link. Converted to an `<a>`, and the route path in the `to` attribute is convert
|
|
|
448
452
|
| Attribute | Description |
|
|
449
453
|
|------|------|
|
|
450
454
|
| `to` | Destination path or URL. Paths starting with `/` are treated as internal paths (basename is prepended to the pathname; a `?query` / `#hash` suffix is kept as-is). A value starting with `?` is a **query-only** link: the href is assembled as "current pathname + that query" and tracks location changes. Other values are treated as external URLs. |
|
|
455
|
+
| `match` | `exact` (default) or `prefix`. With `prefix` the link is also active on the paths under it — a side navigation's "Products" on `/products/3` — with `aria-current="true"` there (`"page"` on the path itself). |
|
|
451
456
|
|
|
452
457
|
**Active state**: The generated `<a>` receives the `active` class when its path matches the current location, and `aria-current="page"` alongside it — the same fact, expressed in ARIA, so screen readers announce the current page in navigation. The comparison uses the **pathname only** — queries on either side never affect it (so `to="/products"` stays active on `/products?page=2`, and a query-only link is active whenever you are on its page). Tracking is updated on navigation events (`currententrychange`, `wcs:navigate`, `popstate`).
|
|
453
458
|
|
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}}const c="data-wcs-ssr",h="data-wcs-ssr-link",u="@@wcs-route-ph:",d="@@wcs-route-start:",m="@@wcs-route-end:";class p extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=e();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_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 endMarker(){return void 0===this._endMarker&&(this._endMarker=document.createComment(`${m}${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(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 g=Symbol.for("wcstack.trustedTypes.policy"),f=Symbol.for("wcstack.trustedTypes.internal"),_="wcstack";function b(){const t=globalThis[g];return null===t||"object"!=typeof t?null:t}let y=!1;function w(t){const e=function(){const t=globalThis,e=t[f];if(void 0!==e)return e;const a=globalThis.trustedTypes;let n=null;if(a&&"function"==typeof a.createPolicy)try{n=a.createPolicy(_,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof b()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${_}". Allow it in the CSP (\`trusted-types ${_};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[f]=n,n}(),a=e?.createHTML;if("function"==typeof a)return a.call(e,t);if(!("trustedTypes"in globalThis))return t;const n=b(),s=n?.createHTML;return"function"==typeof s?(y||(y=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${_}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${_};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(n,t)):t}const N=new Map;class v 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 N.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)N.has(e)?n.innerHTML=w(N.get(e)||""):n.innerHTML=w(await this._loadTemplateFromSource(e)||"");else if(a){const e=this._loadTemplateFromDocument(a);e?n.innerHTML=w(e):console.warn(`${t.tagNames.layout} could not find template with id "${a}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&t.enableShadowRoot}get name(){return this.getAttribute("name")||""}}class C extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||a(`${t.tagNames.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&t.enableShadowRoot}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const P=new Set(["props","states","attr",""]);function k(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 E(t,e){t.hasAttribute("data-bind")||a(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";P.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&&k(t,e,s)}).catch(()=>{a(`Failed to define custom element: ${i}`)}):k(t,e,s)}const A=Symbol.for("wcstack.binder");function S(){const t=globalThis[A];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const $=Symbol.for("wcstack.binder.pending"),x=Symbol.for("wcstack.binder.taken");function T(){const t=globalThis;let e=t[x];return void 0===e&&(e=new WeakSet,t[x]=e),e}function R(t,e){const a=S();return null===a?(function(){const t=globalThis;let e=t[$];return void 0===e&&(e=[],t[$]=e),e}().push(t),!1):(T().add(t),a.bind(t,e),!0)}const L={range:!0};function H(t,e){for(const a of t.routeChildNodes)e.add(a.placeHolder).add(a.endMarker),H(a,e);return e}function z(t){const e=t.placeHolder,a=t.endMarker,n=null!==a.parentNode&&a.parentNode===e.parentNode&&!!(4&e.compareDocumentPosition(a)),s=n?null:H(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 I 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)}!function(t){if(null!==S())for(const e of t)1===e.nodeType&&R(e,L)}(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=>{E(e,t)}),e.hasAttribute("data-bind")&&E(e,t))}}function M(){return document.createElement(t.tagNames.layoutOutlet)}const O="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";async function F(t,e){let n=null,s=null;const i=e.uuid||"",r=`\n//# sourceURL=${i?`wcs-guard-handler:${i}`:"wcs-guard-handler"}\n`,o=t.text+r;let l=!1;const 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){await new Promise(t=>setTimeout(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: give the page's nonce to the <script> that loads @wcstack/router, or allow blob: in script-src. See ${O}`:`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 ${O}`}(t,s,l),{cause:s??t})}}}finally{document.removeEventListener("securitypolicyviolation",c)}return n&&"function"==typeof n.default?n.default:null}function U(t,e){F(t,e).then(t=>{t?e.guardHandler=t:e.notifyGuardHandlerLoadFailed()}).catch(t=>{console.error("loadGuardHandler failed:",t),e.notifyGuardHandlerLoadFailed()})}function W(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(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),W(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&&U(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=M();n.layout=a,o=n,l=e}}const h=await D(e,l,n,s);l.replaceChildren(),l.appendChild(h),r.appendChild(o)}else r.appendChild(a);return r}async function j(t){const e=new Map;return await D(t,t.template.content,[],e)}const G=new WeakSet;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 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)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 e=t.basenameFileExtensions;return 0===e.length?null:(Y===e&&J||(Y=e,J=new RegExp(`\\/[^/]+(?:${e.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=z(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(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=>{E(t,e.typedParams)}),n.hasAttribute("data-bind")&&E(n,e.typedParams),n.querySelectorAll(t.tagNames.layoutOutlet).forEach(t=>{t.assignParams(e.typedParams)}),n.tagName.toLowerCase()===t.tagNames.layoutOutlet&&n.assignParams(e.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!==S()||(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(R(e,L))continue}else if(null!==S())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 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 mt(e,n,s,i,r=""){const o=Z(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=V(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 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}(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&&q(e,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}const bt=new WeakMap;function yt(t,e,a){const n=function(t,e){let a=bt.get(t);return void 0===a&&(a=new Map,bt.set(t,a)),a.has(e)||a.set(e,t.getAttribute(e)),a.get(e)}(t,e);!function(t,e,a){null===a?t.removeAttribute(e):t.setAttribute(e,a)}(t,e,void 0===a?n:null===a?null:String(a))}function wt(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const Nt=Object.freeze({});class vt 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=Nt;_typedParams=Nt;_searchParams=Nt;_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}set basename(t){yt(this,"basename",t)}_getOutlet(){const e=this.nextElementSibling;if(e&&e.matches(t.tagNames.outlet))return e;!function(e){const a=e.getRootNode();if(a.nodeType!==Node.DOCUMENT_NODE&&a.nodeType!==Node.DOCUMENT_FRAGMENT_NODE)return;const n=t.tagNames.router,s=t.tagNames.outlet;for(const t of a.querySelectorAll(s))G.has(t)||t.previousElementSibling?.matches(n)||(G.add(t),console.warn(`[@wcstack/router] [wcs/router-outlet-misplaced] A <${n}> uses only the element right after it as its outlet, and this page has a <${s}> that no router uses. The router makes an outlet of its own right after itself, so the routes render there and the <${s}> you placed stays empty. Move the <${s}> right after the <${n}>.`,t))}(this);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=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(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(Z(n,this._basename)),i=s&&("push"===e.navigationType||"replace"===e.navigationType),r=a.search,o=this;e.intercept({handler:async()=>{try{await mt(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 mt(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const e=wt();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 j(this),o=!e&&this._outlet.hasAttribute(c);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(c);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!==S())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(e){const a=this.outlet.rootNode,n=new Map;let s=!1;if(this._forEachRoute(t=>{n.has(t.absolutePath)?s=!0:n.set(t.absolutePath,t)}),s)return!1;if(null!==a.querySelector(t.tagNames.layoutOutlet))return!1;const i=new Map,r=new Map,o=new Map,l=document.createTreeWalker(a,NodeFilter.SHOW_COMMENT);let h=0;for(;l.nextNode();){const t=l.currentNode,e=t.data;if(h++,e.startsWith(u)){const a=e.slice(15);if(i.has(a)||!n.has(a))return!1;i.set(a,t)}else if(e.startsWith(d)){const a=e.slice(18);if(r.has(a)||!n.has(a))return!1;r.set(a,{comment:t,index:h})}else if(e.startsWith(m)){const a=e.slice(16);if(o.has(a)||!n.has(a))return!1;o.set(a,{comment:t,index:h})}}if(r.size!==o.size)return!1;const p=[];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;p.push({start:e.index,end:a.index})}for(const t of p)for(const e of p)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const g=Z(e,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 e of f.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(d)){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,n)}for(const{comment:t}of r.values())t.remove();this.outlet.removeAttribute(c);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(e){const n=Z(e,this._basename),s=V(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 mt(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${u}${t.absolutePath}`}),this.outlet.setAttribute(c,"");for(const t of this.outlet.lastRoutes)t.placeHolder.after(document.createComment(`${d}${t.absolutePath}`))}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&e.isConnected&&R(e,L)}_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),wt()){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 Ct=["title","rel","target","download","hreflang","lang","dir"];class Pt extends HTMLElement{static get observedAttributes(){return["to",...Ct]}_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 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(e,n){if(this._isInternalTarget(n)){const{pathname:t,search:a,hash:s}=gt(n),i=""===t?window.location.pathname:this._joinInternalPath(this.router.basename,t);e.href=i+ft(a)+s}else try{e.href=new URL(n).toString()}catch{a(`[${t.tagNames.link}] Invalid URL in 'to' attribute: ${n}`)}}connectedCallback(){wt()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(h)?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(h),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-")||Ct.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,wt())return this._updateActiveState(),void a.setAttribute(h,"");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(Ct.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 kt=[],Et=new Map;let At=!1;const St=new WeakMap;class $t 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(),At||(this._captureInitialHead(),At=!0),kt.push(this),this._reapplyHead()}disconnectedCallback(){const t=kt.indexOf(this);-1!==t&&kt.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||a("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=St.get(t);if(void 0!==e)return e;const a=this._computeKey(t);return St.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);Et.has(t)||Et.set(t,e.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of kt)for(const a of t._childElementArray)e.add(this._getKey(a));for(const t of Et.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=kt.length-1;t>=0;t--){const a=kt[t];for(const t of a._childElementArray)if(this._getKey(t)===n){e=t.cloneNode(!0);break}if(e)break}if(!e&&Et.has(n)){e=Et.get(n).cloneNode(!0)}const s=a.get(n)??null;e?(s?s.replaceWith(e):document.head.appendChild(e),a.set(n,e),R(e)||ht(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 xt(e=customElements){e.get(t.tagNames.layout)||e.define(t.tagNames.layout,v),e.get(t.tagNames.layoutOutlet)||e.define(t.tagNames.layoutOutlet,I),e.get(t.tagNames.outlet)||e.define(t.tagNames.outlet,C),e.get(t.tagNames.route)||e.define(t.tagNames.route,p),e.get(t.tagNames.router)||e.define(t.tagNames.router,vt),e.get(t.tagNames.link)||e.define(t.tagNames.link,Pt),e.get(t.tagNames.head)||e.define(t.tagNames.head,$t)}var Tt;await void xt(Tt);
|
|
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=!1,e.hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",this.enableGuard())}enableGuard(){this._hasGuard||(this._hasGuard=!0,this._guardFallbackPath||="/",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}}const h="data-wcs-ssr",c="data-wcs-ssr-link",u="@@wcs-route-ph:",d="@@wcs-route-start:",m="@@wcs-route-end:";class p extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=e();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_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 endMarker(){return void 0===this._endMarker&&(this._endMarker=document.createComment(`${m}${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()}enableGuard(){this._core.enableGuard()}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 f=Symbol.for("wcstack.trustedTypes.policy"),g=Symbol.for("wcstack.trustedTypes.internal"),_="wcstack";function b(){const t=globalThis[f];return null===t||"object"!=typeof t?null:t}let y=!1;function w(t){const e=function(){const t=globalThis,e=t[g];if(void 0!==e)return e;const a=globalThis.trustedTypes;let n=null;if(a&&"function"==typeof a.createPolicy)try{n=a.createPolicy(_,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof b()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${_}". Allow it in the CSP (\`trusted-types ${_};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[g]=n,n}(),a=e?.createHTML;if("function"==typeof a)return a.call(e,t);if(!("trustedTypes"in globalThis))return t;const n=b(),s=n?.createHTML;return"function"==typeof s?(y||(y=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${_}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${_};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(n,t)):t}const N=new Map;class v 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 N.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)N.has(e)?n.innerHTML=w(N.get(e)||""):n.innerHTML=w(await this._loadTemplateFromSource(e)||"");else if(a){const e=this._loadTemplateFromDocument(a);e?n.innerHTML=w(e):console.warn(`${t.tagNames.layout} could not find template with id "${a}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&t.enableShadowRoot}get name(){return this.getAttribute("name")||""}}class C extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||a(`${t.tagNames.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&t.enableShadowRoot}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const P=new Set(["props","states","attr",""]);function k(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 E(t,e){t.hasAttribute("data-bind")||a(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";P.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&&k(t,e,s)}).catch(()=>{a(`Failed to define custom element: ${i}`)}):k(t,e,s)}const A=Symbol.for("wcstack.binder");function S(){const t=globalThis[A];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const $=Symbol.for("wcstack.binder.pending"),x=Symbol.for("wcstack.binder.taken");function T(){const t=globalThis;let e=t[x];return void 0===e&&(e=new WeakSet,t[x]=e),e}function R(t,e){const a=S();return null===a?(function(){const t=globalThis;let e=t[$];return void 0===e&&(e=[],t[$]=e),e}().push(t),!1):(T().add(t),a.bind(t,e),!0)}const L={range:!0};function H(t,e){for(const a of t.routeChildNodes)e.add(a.placeHolder).add(a.endMarker),H(a,e);return e}function z(t){const e=t.placeHolder,a=t.endMarker,n=null!==a.parentNode&&a.parentNode===e.parentNode&&!!(4&e.compareDocumentPosition(a)),s=n?null:H(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 I 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)}!function(t){if(null!==S())for(const e of t)1===e.nodeType&&R(e,L)}(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=>{E(e,t)}),e.hasAttribute("data-bind")&&E(e,t))}}function M(){return document.createElement(t.tagNames.layoutOutlet)}const O="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";async function U(t,e){let n=null,s=null;const i=e.uuid||"",r=`\n//# sourceURL=${i?`wcs-guard-handler:${i}`:"wcs-guard-handler"}\n`,o=t.text+r;let l=!1;const h=t=>{t.effectiveDirective.startsWith("script-src")&&(l=!0)};document.addEventListener("securitypolicyviolation",h);try{if("function"==typeof URL.createObjectURL){const t=new Blob([o],{type:"application/javascript"}),e=URL.createObjectURL(t);try{n=await import(e)}catch(t){s=t}finally{URL.revokeObjectURL(e)}}if(!n){const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(o)));try{n=await import(`data:application/javascript;base64,${t}`)}catch(t){await new Promise(t=>setTimeout(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: give the page's nonce to the <script> that loads @wcstack/router, or allow blob: in script-src. See ${O}`:`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 ${O}`}(t,s,l),{cause:s??t})}}}finally{document.removeEventListener("securitypolicyviolation",h)}return n&&"function"==typeof n.default?n.default:null}function F(e,a){U(e,a).then(e=>{e?a.guardHandler=e:(console.error(`${t.tagNames.guardHandler}: the <script type="module"> has no default-exported function, so the route's guard redirects every navigation.`),a.notifyGuardHandlerLoadFailed())}).catch(t=>{console.error("loadGuardHandler failed:",t),a.notifyGuardHandlerLoadFailed()})}function W(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(e,a,n,s){const i=n.length>0?n[n.length-1]:null,r=document.createDocumentFragment(),o=Array.from(a.childNodes);for(const a of o)if(a.nodeType===Node.ELEMENT_NODE){let o=a,l=a;const h=l.tagName.toLowerCase();if(h===t.tagNames.route){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const a=document.importNode(l,!0);customElements.upgrade(a),a.appendChild(t);const r=a;r.initialize(e,i),W(s,r),n.push(r),o=r.placeHolder,l=r}else{if(h===t.tagNames.guardHandler){if(n.length>0){const t=n[n.length-1],e=l.querySelector('script[type="module"]');e&&(t.enableGuard(),F(e,t))}continue}if("template"===h){r.appendChild(l);continue}if(h===t.tagNames.layout){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const e=document.importNode(l,!0);customElements.upgrade(e),e.appendChild(t);const a=e,n=M();n.layout=a,o=n,l=e}}const c=await D(e,l,n,s);l.replaceChildren(),l.appendChild(c),r.appendChild(o)}else r.appendChild(a);return r}async function j(t){const e=new Map;return await D(t,t.template.content,[],e)}const G=new WeakSet;function B(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(q(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(q(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 q(t){return!1!==t.checkVisibility?.()}function K(t,e,a,n){const i=function(t,e,a){const n={},i={};let r=!0,o=!1,l=0,h=0;for(;l<t.absoluteSegmentInfos.length;){const e=t.absoluteSegmentInfos[l];if(e.isIndex){l++;continue}if(0===l&&""===e.segmentText&&"static"===e.type){l++;continue}const c=a[h];if(void 0===c){r=!1;break}let u=!1;if("param"===e.type){const t=e.paramType||"any",a=s[t].parse(c);void 0!==a&&(e.paramName&&(n[e.paramName]=c,i[e.paramName]=a),u=!0)}else u=null!==e.pattern.exec(c);if(!u){r=!1;break}if("catch-all"===e.type){const t=a.slice(h).join("/");n["*"]=t,i["*"]=t,o=!0;break}l++,h++}let c=!1;return r&&(o||l===t.absoluteSegmentInfos.length&&h===a.length)&&(c=!0),c?{path:e,routes:t.routes,params:n,typedParams:i,lastPath:""}:null}(t,e,a);i&&n.push(i);for(const s of t.routeChildNodes)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 e=t.basenameFileExtensions;return 0===e.length?null:(Y===e&&J||(Y=e,J=new RegExp(`\\/[^/]+(?:${e.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=z(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(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=>{E(t,e.typedParams)}),n.hasAttribute("data-bind")&&E(n,e.typedParams),n.querySelectorAll(t.tagNames.layoutOutlet).forEach(t=>{t.assignParams(e.typedParams)}),n.tagName.toLowerCase()===t.tagNames.layoutOutlet&&n.assignParams(e.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,ht="data-wcs";function ct(t,e,a){!lt.has(t)&&function(t){return t.hasAttribute(ht)||null!==t.querySelector(`[${ht}]`)}(t)&&(lt.add(t),function(t){if("complete"!==document.readyState)return void window.addEventListener("load",t,{once:!0});t()}(()=>{var n;null!==S()||(n=t,T().has(n))||console.warn(`[@wcstack/router] ${e} contains ${ht} 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){return"AbortError"===t?.name}const dt=new WeakMap;function mt(t){for(const e of t.childNodeArray)if(1===e.nodeType){if(e.isConnected){if(R(e,L))continue}else if(null!==S())continue;ct(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 pt(e,a){try{let t=null;for(const e of a.routes){const n=await e.guardCheck(a);n&&(t=null===t?n:Object.assign({},t,n))}a.data=t,dt.delete(e)}catch(s){if(s instanceof n){const n=(dt.get(e)??0)+1;return n>10?(dt.delete(e),console.error(`${t.tagNames.router}: guard redirect loop — stopped after 10 redirects in a row (the last: ${a.path} → ${s.fallbackPath}). The guards of these routes send each other back and forth.`),!1):(dt.set(e,n),e.connectedCallbackPromise.catch(()=>{}).then(()=>e.replace(s.fallbackPath)).catch(t=>{ut(t)||console.error("Fallback navigation failed:",t)}),!1)}throw s}return!0}async function ft(e,n,s,i,r=""){const o=Z(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=V(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 h=n.lastRoutes,c=await async function(t,e,a,n){if(!await pt(t,e))return!1;n?.();const s=new Set(e.routes),i=new Set(a),r=()=>{for(const t of a)s.has(t)||at(t);const t=[];for(const a of e.routes)(t.length>0||!i.has(a)||a.shouldChange(e.params))&&(t.push(a),nt(a,e));let n=!1;for(const e of t){const t=i.has(e);t&&n||it(e),n||=t,a.length>0&&!t&&mt(e)}};let o;return 0===a.length?r():o=ot("router",r),void 0!==o&&await o,!0}(e,l,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},!0)});return!!c&&(e.releasePath(),n.lastRoutes=l.routes,h.length>0&&B(e,l),!0)}function gt(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function _t(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 bt(t){return"?"===t?"":t}function yt(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}const wt=new WeakMap;function Nt(t,e,a){const n=function(t,e){let a=wt.get(t);return void 0===a&&(a=new Map,wt.set(t,a)),a.has(e)||a.set(e,t.getAttribute(e)),a.get(e)}(t,e);!function(t,e,a){null===a?t.removeAttribute(e):t.setAttribute(e,a)}(t,e,void 0===a?n:null===a?null:String(a))}function vt(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const Ct=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"},{name:"leaveConfirm",attribute:"leave-confirm"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=Ct;_typedParams=Ct;_searchParams=Ct;_routeName="";_data=null;_hasCommitted=!1;_pathHeld=!1;_leaveChecked=!1;_leaveConfirmed=!1;_listeningUnload=!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}set basename(t){Nt(this,"basename",t)}get leaveConfirm(){return this.getAttribute("leave-confirm")||null}set leaveConfirm(t){Nt(this,"leave-confirm",t),this._syncBeforeUnload()}_onBeforeUnload=t=>{null!==this.leaveConfirm&&t.preventDefault()};_syncBeforeUnload(){const t=this.isConnected&&null!==this.leaveConfirm&&!vt();t!==this._listeningUnload&&(this._listeningUnload=t,t?window.addEventListener("beforeunload",this._onBeforeUnload):window.removeEventListener("beforeunload",this._onBeforeUnload))}_confirmLeave(t){const e=this.leaveConfirm;return!(null!==e&&this._hasCommitted&&!this._leaveConfirmed&&!this.isSameMatch(Z(this._normalizePathname(t),this._basename)))||(this._leaveConfirmed=window.confirm(e))}_getOutlet(){const e=this.nextElementSibling;if(e&&e.matches(t.tagNames.outlet))return e;!function(e){const a=e.getRootNode();if(a.nodeType!==Node.DOCUMENT_NODE&&a.nodeType!==Node.DOCUMENT_FRAGMENT_NODE)return;const n=t.tagNames.router,s=t.tagNames.outlet;for(const t of a.querySelectorAll(s))G.has(t)||t.previousElementSibling?.matches(n)||(G.add(t),console.warn(`[@wcstack/router] [wcs/router-outlet-misplaced] A <${n}> uses only the element right after it as its outlet, and this page has a <${s}> that no router uses. The router makes an outlet of its own right after itself, so the routes render there and the <${s}> you placed stays empty. Move the <${s}> right after the <${n}>.`,t))}(this);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,e=!1){const a=Object.freeze({...t.params}),n=Object.freeze({...t.typedParams}),s=i(t.search),o=t.data??null,l=this._data!==o,h=!r(this._params,a),c=this._routeName!==t.routeName,u=!r(this._searchParams,s),d=this._path!==t.path;l&&(this._data=o),h&&(this._params=a,this._typedParams=n),c&&(this._routeName=t.routeName),u&&(this._searchParams=s),this._path=t.path,this._hasCommitted=!0,this._leaveConfirmed=!1,l&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),h&&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})),u&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),this._pathHeld=d&&e,d&&!e&&this._firePathChanged()}releasePath(){this._pathHeld&&(this._pathHeld=!1,this._firePathChanged())}_firePathChanged(){this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:this._path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(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=>{ut(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=>{ut(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=_t(t),n=""!==a.pathname||""===a.search&&""===a.hash?this._joinInternalPath(this._basename,a.pathname):window.location.pathname,s=n+bt(a.search)+a.hash;if(null!==this.leaveConfirm&&(await Promise.resolve(),!this._confirmLeave(n)))return;const i=gt();if(i?.navigate){let t;this._leaveChecked=!0;try{t=e?i.navigate(s,{history:"replace"}):i.navigate(s)}finally{this._leaveChecked=!1}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 ft(this,this.outlet,t,this._path,bt(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.defaultPrevented||e.hashChange||null!==e.downloadRequest)return;const a=new URL(e.destination.url),n=this._normalizePathname(a.pathname);if(!this._isOwnPath(n))return;if(!this._leaveChecked&&!1!==e.cancelable&&!this._confirmLeave(n))return void e.preventDefault?.();const s=this.isSameMatch(Z(n,this._basename)),i=s&&("push"===e.navigationType||"replace"===e.navigationType),r=a.search,o=this;e.intercept({handler:async()=>{try{await ft(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 ft(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const e=vt();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 j(this),o=!e&&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&&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(h);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(r)}await ft(this,this.outlet,l,this._path,window.location.search||""),(o||null!==S())&&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(u)){const a=e.slice(15);if(i.has(a)||!n.has(a))return!1;i.set(a,t)}else if(e.startsWith(d)){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(m)){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 p=[];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;p.push({start:e.index,end:a.index})}for(const t of p)for(const e of p)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const f=Z(e,this._basename);let g=V(this,f);if(!g){if(null===this._fallbackRoute)return!1;g={routes:[this._fallbackRoute],params:{},typedParams:{},path:f,lastPath:this._path}}if(g.lastPath=this._path,g.routes.length!==r.size)return!1;for(const t of g.routes)if(!r.has(t.absolutePath))return!1;const _=new Set;for(const t of this.routeChildNodes)_.add(t.absolutePath);for(const t of g.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 e of g.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(d)){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,n)}for(const{comment:t}of r.values())t.remove();this.outlet.removeAttribute(h);for(const t of g.routes)nt(t,g);return this.outlet.lastRoutes=g.routes,!await pt(this,g)||(this.commitNavigation({params:g.params,typedParams:g.typedParams,routeName:g.routes[g.routes.length-1].name,data:g.data??null,search:window.location.search||"",path:f}),!0)}async _renderForSsr(e){const n=Z(e,this._basename),s=V(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 ft(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${u}${t.absolutePath}`}),this.outlet.setAttribute(h,"");for(const t of this.outlet.lastRoutes)t.placeHolder.after(document.createComment(`${d}${t.absolutePath}`))}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&e.isConnected&&R(e,L)}_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(!yt(t,a))continue;const n=t,s=n[a];delete n[a],n[a]=s}}(this),this._syncBeforeUnload(),vt()){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=gt();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&&(gt()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),this._syncBeforeUnload(),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const kt=["title","rel","target","download","hreflang","lang","dir"];class Et extends HTMLElement{static get observedAttributes(){return["to","match",...kt]}_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 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(e,n){if(this._isInternalTarget(n)){const{pathname:t,search:a,hash:s}=_t(n),i=""===t?window.location.pathname:this._joinInternalPath(this.router.basename,t);e.href=i+bt(a)+s}else try{e.href=new URL(n).toString()}catch{a(`[${t.tagNames.link}] Invalid URL in 'to' attribute: ${n}`)}}connectedCallback(){vt()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(c)?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(c),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-")||kt.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,vt())return this._updateActiveState(),void a.setAttribute(c,"");gt()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!gt()?.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(){gt()?.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("match"!==t||e===a){if("to"===t&&e!==a)this._path=a||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(kt.includes(t)){const e=this._anchorElement;e&&(null===a?e.removeAttribute(t):e.setAttribute(t,a))}}else this._updateActiveState()}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const t=this._normalizePathname(new URL(window.location.href).pathname),{pathname:e}=_t(this._path),a=this._normalizePathname(this._isInternalTarget(this._path)?""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e):e),n=t===a,s=!n&&"prefix"===this.getAttribute("match")&&t.startsWith(a+"/");this._anchorElement&&(n||s?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current",n?"page":"true")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const At=[],St=new Map;let $t=!1;const xt=new WeakMap;class Tt 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(),$t||(this._captureInitialHead(),$t=!0),At.push(this),this._reapplyHead()}disconnectedCallback(){const t=At.indexOf(this);-1!==t&&At.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||a("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=xt.get(t);if(void 0!==e)return e;const a=this._computeKey(t);return xt.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);St.has(t)||St.set(t,e.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of At)for(const a of t._childElementArray)e.add(this._getKey(a));for(const t of St.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=At.length-1;t>=0;t--){const a=At[t];for(const t of a._childElementArray)if(this._getKey(t)===n){e=t.cloneNode(!0);break}if(e)break}if(!e&&St.has(n)){e=St.get(n).cloneNode(!0)}const s=a.get(n)??null;e?(s?s.replaceWith(e):document.head.appendChild(e),a.set(n,e),R(e)||ct(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 Rt(e=customElements){e.get(t.tagNames.layout)||e.define(t.tagNames.layout,v),e.get(t.tagNames.layoutOutlet)||e.define(t.tagNames.layoutOutlet,I),e.get(t.tagNames.outlet)||e.define(t.tagNames.outlet,C),e.get(t.tagNames.route)||e.define(t.tagNames.route,p),e.get(t.tagNames.router)||e.define(t.tagNames.router,Pt),e.get(t.tagNames.link)||e.define(t.tagNames.link,Et),e.get(t.tagNames.head)||e.define(t.tagNames.head,Tt)}var Lt;await void Rt(Lt);
|
|
2
2
|
//# sourceMappingURL=auto.min.js.map
|