diff --git a/framework-views/Build-DocfxFrameworkViews.ps1 b/framework-views/Build-DocfxFrameworkViews.ps1 index 70be7c0..6787fbb 100644 --- a/framework-views/Build-DocfxFrameworkViews.ps1 +++ b/framework-views/Build-DocfxFrameworkViews.ps1 @@ -301,9 +301,13 @@ try { $root = if ($view -ceq $defaultView) { '""' } else { "/_frameworks/$directory" } ' ~^{0}$ {1};' -f [regex]::Escape($directory), $root } - Write-Json "$site/framework-views.json" ([ordered]@{ schemaVersion = 1; apiPath = "/$ApiPath/"; defaultView = $defaultView; viewOrder = @($views.Keys); views = $views }) + $availability = Get-FrameworkPageAvailability $site $ApiPath $defaultView $views + Merge-SharedNavigationToc $site $work $buildDestination $ApiPath $defaultView $views $availability + $fallbackRoutes = Get-FrameworkNginxFallbackRules $defaultView $views + Write-Json "$site/framework-views.json" ([ordered]@{ schemaVersion = 1; apiPath = "/$ApiPath/"; defaultView = $defaultView; viewOrder = @($views.Keys); views = $views; availability = $availability }) (Get-Content -LiteralPath "$PSScriptRoot/framework-views.nginx.conf" -Raw).Replace('__API__', "/$ApiPath/"). - Replace('__VIEWS__', ($routes -join "`n")).Replace('__SEARCH__', ($searchRoutes -join "`n")) | Set-Content -LiteralPath "$work/nginx.conf" + Replace('__VIEWS__', ($routes -join "`n")).Replace('__SEARCH__', ($searchRoutes -join "`n")). + Replace('__FALLBACK__', ($fallbackRoutes -join "`n")) | Set-Content -LiteralPath "$work/nginx.conf" Write-Host "Site: $site" } finally { $outputLock.Dispose() diff --git a/framework-views/FrameworkViewConventions.ps1 b/framework-views/FrameworkViewConventions.ps1 index 0737c11..bd3afce 100644 --- a/framework-views/FrameworkViewConventions.ps1 +++ b/framework-views/FrameworkViewConventions.ps1 @@ -83,3 +83,110 @@ function Get-FrameworkOutputEntries([string] $Path, [string] $OwnershipFile, [st $links = Get-ChildItem -LiteralPath $Path -Force -Recurse -Attributes ReparsePoint | Select-Object -First 1 if ($links) { throw "Framework output contains a link. Move '$($links.FullName)' before rebuilding." } } + +function Get-FrameworkPageAvailability([string] $SiteRoot, [string] $ApiPath, [string] $DefaultView, $Views) { + $pageViews = [Collections.Generic.Dictionary[string, Collections.Generic.List[string]]]::new([StringComparer]::Ordinal) + foreach ($view in $Views.Keys) { + $viewApiRoot = if ($view -ceq $DefaultView) { + Join-Path $SiteRoot $ApiPath + } else { + Join-Path $SiteRoot "_frameworks/$($Views[$view].directory)/$ApiPath" + } + if (!(Test-Path -LiteralPath $viewApiRoot -PathType Container)) { continue } + foreach ($file in [IO.Directory]::EnumerateFiles($viewApiRoot, '*.html', [IO.SearchOption]::AllDirectories)) { + $relative = [IO.Path]::GetRelativePath($viewApiRoot, $file).Replace('\', '/') + if (!$pageViews.ContainsKey($relative)) { + $pageViews[$relative] = [Collections.Generic.List[string]]::new() + } + $pageViews[$relative].Add($view) + } + } + + $setIndexes = [Collections.Generic.Dictionary[string, int]]::new([StringComparer]::Ordinal) + $sets = [Collections.Generic.List[string[]]]::new() + $pages = [ordered]@{} + $sortedKeys = [string[]]$pageViews.Keys + [Array]::Sort($sortedKeys, [StringComparer]::Ordinal) + foreach ($relative in $sortedKeys) { + $available = $pageViews[$relative].ToArray() + $key = $available -join ',' + if (!$setIndexes.ContainsKey($key)) { + $setIndexes[$key] = $sets.Count + $sets.Add($available) + } + $pages[$relative] = $setIndexes[$key] + } + [ordered]@{ sets = $sets.ToArray(); pages = $pages } +} + +function Get-FrameworkNginxFallbackRules([string] $DefaultView, $Views) { + foreach ($view in $Views.Keys) { + $prefix = if ($view -ceq $DefaultView) { '' } else { "/_frameworks/$($Views[$view].directory)" } + ' if (-f $document_root{0}$framework_fallback_target) {{ return 302 $uri?${{framework_query_prefix}}view={1}; }}' -f $prefix, $view + } +} + +function Resolve-FrameworkApiRelativePage([string] $Href, [string] $ApiPrefix) { + if (!$Href) { return $null } + $normalized = ($Href -split '[?#]', 2)[0].TrimStart('/') + if (!$normalized.StartsWith($ApiPrefix, [StringComparison]::Ordinal)) { return $null } + $relative = $normalized.Substring($ApiPrefix.Length) + if (!$relative -or $relative.EndsWith('/')) { "${relative}index.html" } else { $relative } +} + +function Merge-NavigationTocItems($TargetItems, $CandidateItemLists, [string] $ApiPrefix, $Availability) { + $changed = $false + if (!$TargetItems) { return $false } + for ($index = 0; $index -lt $TargetItems.Count; $index++) { + $item = $TargetItems[$index] + $href = if ($item.Contains('href')) { $item['href'] } + $relative = Resolve-FrameworkApiRelativePage $href $ApiPrefix + if ($relative -and !$Availability.pages.Contains($relative)) { + foreach ($candidateList in $CandidateItemLists) { + if (!$candidateList -or $index -ge $candidateList.Count) { continue } + $candidate = $candidateList[$index] + $candidateHref = if ($candidate.Contains('href')) { $candidate['href'] } + $candidateRelative = Resolve-FrameworkApiRelativePage $candidateHref $ApiPrefix + if ($candidateRelative -and $Availability.pages.Contains($candidateRelative)) { + $item['href'] = $candidateHref + foreach ($field in 'topicHref', 'tocHref') { + if ($candidate.Contains($field)) { $item[$field] = $candidate[$field] } + } + $changed = $true + break + } + } + } + if ($item.Contains('items') -and $item['items']) { + $childCandidates = @( + foreach ($candidateList in $CandidateItemLists) { + if ($candidateList -and $index -lt $candidateList.Count -and $candidateList[$index].Contains('items')) { + , $candidateList[$index]['items'] + } + } + ) + if (Merge-NavigationTocItems $item['items'] $childCandidates $ApiPrefix $Availability) { $changed = $true } + } + } + $changed +} + +function Merge-SharedNavigationToc([string] $SiteRoot, [string] $WorkRoot, [string] $BuildDestination, [string] $ApiPath, [string] $DefaultView, $Views, $Availability) { + $tocPath = Join-Path $SiteRoot 'toc.json' + if (!(Test-Path -LiteralPath $tocPath -PathType Leaf)) { return } + $targetToc = Read-Json $tocPath + if (!$targetToc -or !$targetToc.Contains('items')) { return } + $candidateLists = @( + foreach ($view in $Views.Keys) { + if ($view -ceq $DefaultView) { continue } + $candidatePath = Join-Path $WorkRoot "$($Views[$view].directory)/$BuildDestination/toc.json" + if (!(Test-Path -LiteralPath $candidatePath -PathType Leaf)) { continue } + $candidateToc = Read-Json $candidatePath + if ($candidateToc -and $candidateToc.Contains('items')) { , $candidateToc['items'] } + } + ) + if (!$candidateLists.Count) { return } + if (Merge-NavigationTocItems $targetToc['items'] $candidateLists "$ApiPath/" $Availability) { + Write-Json $tocPath $targetToc + } +} diff --git a/framework-views/README.md b/framework-views/README.md index 5df38cb..3b5fd2d 100644 --- a/framework-views/README.md +++ b/framework-views/README.md @@ -28,14 +28,20 @@ The generator uses the deepest common directory of the `metadata.dest` paths as DocFX owns project mappings, filters, exclusions, overwrites and other metadata options. MSBuild supplies each mapped project's evaluated target frameworks, including inherited values. Remove any `TargetFramework` metadata property so the generator can choose the target per view. A project contributes documentation only to its evaluated targets. Unsupported TFMs, including platform-qualified TFMs, fail with the project path and the target in the diagnostic. -The default view is the first discovered target in this order. The same order determines fallback precedence. +The default view is the first discovered target in this order. The same order determines fallback precedence everywhere (hyperlinks, framework selector, and server-side HTTP routing): 1. Modern .NET, by descending numeric version 2. .NET Core, by descending numeric version 3. .NET Standard, by descending numeric version 4. .NET Framework, by descending numeric version -For example, the order is `net11.0`, `net10.0`, `net9.0`, `netcoreapp3.1`, `netstandard2.1`, `netstandard2.0`, `net481`, `net48`, `net462`. New unqualified versions follow the same rules when the installed SDK and DocFX support them. +For example, the order is `net11.0`, `net10.0`, `netstandard2.1`, `netstandard2.0`, `net481`, `net48`, `net462`. New unqualified versions follow the same rules when the installed SDK and DocFX support them. + +The selected framework is treated as a preference rather than an unconditional routing constraint: + +- Whenever a destination API page exists in the requested framework, that framework is preserved. +- Whenever a destination API page does not exist in the requested framework, resolution selects the first framework in precedence order that contains the destination (whether that target is the default framework or a non-default framework). +- Pages that do not exist in any framework return HTTP 404, and unknown framework identifiers return HTTP 400. Keep build content, resources, and consumer template overlays under the configuration directory. Project sources can sit outside it. Omit a site-local entry from `build.xref` if it can resolve UIDs from another view. Duplicate UIDs within a view have the same constraints as a standard DocFX build. @@ -67,9 +73,10 @@ docker run --rm --mount "type=bind,source=$($PWD.Path),target=/workspace" -w /wo ## Outputs and hosting -- `/site/` is the packaged static site. The default view is at the site root. Additional views retain native API HTML, xrefs and search indexes in `_frameworks//`. Shared conceptual pages and assets are published once. -- `/site/framework-views.json` is the schema-version-1 manifest served at `/framework-views.json`. It contains the API root, default view, framework order, and per-view TFM, directory, xref URL and projects. -- `/nginx.conf` serves the public API path and native xref map by exact `?view=` value. Missing or empty view uses the default. Unknown API or xref views receive HTTP 400. Missing pages or slash-terminated directory indexes in a known view receive HTTP 404. The browser selector resolves fallback before navigating. The configuration also serves the view-specific search indexes and keeps physical framework copies internal. +- `/site/` is the packaged static site. The default view is at the site root. Additional views retain native API HTML, xrefs and search indexes in `_frameworks//`. Shared conceptual pages and assets are published once. When shared root navigation (`toc.json`) references an API section absent from the default view, the generator merges its resolved HTML link from the first view in precedence order where it exists. +- `/site/framework-views.json` is the schema-version-1 manifest served at `/framework-views.json`. It contains the API root, default view, framework order, per-view TFM, directory, xref URL and projects, and a compact deduplicated `availability` inventory (`sets` and `pages`) derived from the actual generated native DocFX HTML output. +- `/nginx.conf` serves the public API path and native xref map by exact `?view=` value. Missing or empty view uses the default. Unknown API or xref views (or excess duplicate `view` parameters) receive HTTP 400. For HTML pages and `/`-terminated directory indexes under the API root that are unavailable in the requested view, NGINX checks the generated framework directories in precedence order and responds with HTTP 302 to the resolved public URL (`?view=`), preserving unrelated query parameters while browsers preserve fragments. Pages missing from all views, non-HTML API resources (such as view-isolated `toc.json` files or missing static files), and direct requests under `/_frameworks/` receive HTTP 404 without redirecting. The configuration also serves view-specific search indexes and keeps physical framework copies internal. +- The `ms-style` client script (`public/framework-view.js`) applies the same destination-aware resolution policy across global navigation, TOCs, breadcrumbs, cross-references, search results, ordinary internal API hyperlinks, and the framework selector. Resolved `href` attributes are written directly to anchors so opening links in new tabs works natively without click interception. Single-framework DocFX builds omit `_frameworkApi` and keep standard native behavior. - Per-TFM stage directories and logs are available under the output root for inspection. Use [framework-views.Dockerfile](framework-views.Dockerfile) with a context containing `site/` and `nginx.conf`. It uses a pinned NGINX base by default, accepts `NGINX_IMAGE` as an explicit build argument, checks for the manifest and runs `nginx -t`. A consumer can provide its own Dockerfile or server configuration and preserve the public path, routing, search worker and cache contract. diff --git a/framework-views/framework-views.nginx.conf b/framework-views/framework-views.nginx.conf index 16e208a..941045e 100644 --- a/framework-views/framework-views.nginx.conf +++ b/framework-views/framework-views.nginx.conf @@ -16,6 +16,36 @@ map $uri $framework_directory_index { ~/$ $framework_root${uri}index.html; } +# Only HTML pages and directory indexes participate in destination-aware fallback. +map $uri $framework_fallback_target { + default ""; + ~\.html$ $uri; + ~/$ ${uri}index.html; +} + +# Strip case-insensitive view arguments while preserving unrelated query parameters. +map $args $framework_args_1 { + default $args; + ~*^view=[^&]*&?$ ""; + ~*^view=[^&]*&(?.+)$ $after; + ~*^(?.*)&view=[^&]*&?$ $before; + ~*^(?.*)&view=[^&]*&(?.+)$ $before&$after; +} + +map $framework_args_1 $framework_args_2 { + default $framework_args_1; + ~*^view=[^&]*&?$ ""; + ~*^view=[^&]*&(?.+)$ $after; + ~*^(?.*)&view=[^&]*&?$ $before; + ~*^(?.*)&view=[^&]*&(?.+)$ $before&$after; +} + +map $framework_args_2 $framework_query_prefix { + "" ""; + ~^(?.*)&$ "${clean}&"; + default "${framework_args_2}&"; +} + map $status $fingerprinted_asset_cache_control { default "no-store"; ~^2 "public, max-age=31536000, immutable"; @@ -38,7 +68,13 @@ server { location ^~ __API__ { if ($framework_root = invalid) { return 400 "Unknown documentation view."; } - try_files $framework_root$uri $framework_directory_index =404; + try_files $framework_root$uri $framework_directory_index @framework_fallback; + } + location @framework_fallback { + if ($framework_fallback_target = "") { return 404; } + if ($framework_args_2 ~* "(?:^|&)view=") { return 400 "Unknown documentation view."; } +__FALLBACK__ + return 404; } location = /xrefmap.yml { if ($framework_root = invalid) { return 400 "Unknown documentation view."; } diff --git a/templates/ms-style/public/framework-view.js b/templates/ms-style/public/framework-view.js index d4ea5ae..e8d4306 100644 --- a/templates/ms-style/public/framework-view.js +++ b/templates/ms-style/public/framework-view.js @@ -1,26 +1,40 @@ (() => { const meta = name => document.querySelector(`meta[name="docfx:${name}"]`); + const apiMeta = meta('framework-api'); + if (!apiMeta?.content) return; + const api = apiMeta.content; const current = new URL(location.href); - const api = meta('framework-api').content; + const isApiPage = current.pathname.startsWith(api); // Match NGINX's $arg_view lookup, which is case-insensitive for the argument name. - const view = current.search.match(/(?:^\?|&)view=([^&]*)/i)?.[1]; - if (!current.pathname.startsWith(api)) return; - document.addEventListener('DOMContentLoaded', initializeSelector); - if (!view) return; - - const toc = meta('tocrel'); - if (toc?.content) { - const url = new URL(toc.content, current); - if (url.origin === current.origin && url.pathname.startsWith(api)) { - url.pathname = url.pathname.replace(/\.html$/i, '.json'); - setView(url, view); - toc.content = url.href; + const view = isApiPage ? current.search.match(/(?:^\?|&)view=([^&]*)/i)?.[1] : undefined; + + let manifest = null; + const manifestReady = fetch('/framework-views.json') + .then(response => (response.ok ? response.json() : null)) + .then(data => { + if (data?.schemaVersion === 1 && data.apiPath === api) { + manifest = data; + } + return manifest; + }) + .catch(() => null); + + const searchRoot = view ? `/_framework-search/${meta('framework-directory').content}/` : null; + + if (view) { + const toc = meta('tocrel'); + if (toc?.content) { + const url = new URL(toc.content, current); + if (url.origin === current.origin && url.pathname.startsWith(api)) { + url.pathname = url.pathname.replace(/\.html$/i, '.json'); + setView(url, view); + toc.content = url.href; + } } - } - const searchRoot = `/_framework-search/${meta('framework-directory').content}/`; - const search = meta('rel'); - if (search) search.content = searchRoot; + const search = meta('rel'); + if (search) search.content = searchRoot; + } function setView(url, selected) { for (const key of [...url.searchParams.keys()]) { @@ -29,20 +43,79 @@ url.searchParams.set('view', selected); } + function getUrlView(url) { + return url.search.match(/(?:^\?|&)view=([^&]*)/i)?.[1] || null; + } + + function isPagePath(pathname) { + return pathname.endsWith('.html') || pathname.endsWith('/'); + } + + function resolveAvailableViews(pathname) { + const availability = manifest?.availability; + if (!availability?.pages || !availability?.sets || !pathname.startsWith(api)) return null; + let relative = pathname.slice(api.length); + try { + relative = decodeURIComponent(relative); + } catch { + return null; + } + const lookup = relative === '' || relative.endsWith('/') ? relative + 'index.html' : relative; + const setIndex = availability.pages[lookup]; + if (typeof setIndex !== 'number') return null; + return availability.sets[setIndex] ?? null; + } + + function resolveView(pathname, preferred) { + const available = resolveAvailableViews(pathname); + if (!available?.length) return null; + if (preferred && available.includes(preferred)) return preferred; + return available[0]; + } + function preserveView(anchor) { const href = anchor.getAttribute('href'); if (!href || href.startsWith('#')) return; - const url = new URL(href, current); + let url; + try { + url = new URL(href, current); + } catch { + return; + } if (url.origin !== current.origin) return; - const fromSearch = url.pathname.startsWith(searchRoot); + const fromSearch = Boolean(searchRoot && url.pathname.startsWith(searchRoot)); if (fromSearch) url.pathname = '/' + url.pathname.slice(searchRoot.length); const isApi = url.pathname.startsWith(api); - if (isApi) setView(url, view); - if (fromSearch || isApi) { + + let targetView = null; + let shouldRewrite = fromSearch; + + if (isApi && isPagePath(url.pathname)) { + if (view) { + targetView = resolveView(url.pathname, view) ?? view; + setView(url, targetView); + shouldRewrite = true; + } else if (manifest) { + const order = manifest.viewOrder ?? Object.keys(manifest.views); + const explicit = getUrlView(url); + if (!explicit || order.includes(explicit)) { + const preferred = explicit || manifest.defaultView; + const resolved = resolveView(url.pathname, preferred); + if (resolved && resolved !== preferred) { + targetView = resolved; + setView(url, resolved); + shouldRewrite = true; + } + } + } + } + + if (shouldRewrite) { const canonical = url.pathname + url.search + url.hash; if (canonical !== href) anchor.setAttribute('href', canonical); if (fromSearch && anchor.matches('#search-results .item-title > a')) { - anchor.dataset.frameworkUrl = url.pathname + (isApi ? `?view=${encodeURIComponent(view)}` : '') + url.hash; + const displayView = targetView ?? view; + anchor.dataset.frameworkUrl = url.pathname + (isApi && displayView ? `?view=${encodeURIComponent(displayView)}` : '') + url.hash; } } } @@ -52,7 +125,7 @@ node.querySelectorAll?.('a[href]').forEach(preserveView); } - // DocFX renders the TOC, breadcrumbs, prev/next and search results after the HTML loads. + // DocFX renders the navbar, TOC, breadcrumbs, prev/next and search results after the HTML loads. // Observe href changes too because its renderer reuses links on search and TOC updates. new MutationObserver(records => { for (const record of records) { @@ -62,7 +135,13 @@ }).observe(document.documentElement, { subtree: true, childList: true, attributes: true, attributeFilter: ['href'] }); - document.addEventListener('DOMContentLoaded', () => updateLinks(document)); + document.addEventListener('DOMContentLoaded', () => { + updateLinks(document); + if (isApiPage) initializeSelector(); + }); + manifestReady.then(data => { + if (data) updateLinks(document); + }); function frameworkName(entry) { const framework = /^net([1-4])(\d)(\d*)$/.exec(entry.tfm); @@ -91,23 +170,16 @@ const article = document.querySelector('article[data-uid]'); if (!container || !article?.dataset.uid) return; - let manifest; - try { - const response = await fetch('/framework-views.json'); - if (!response.ok) return; - manifest = await response.json(); - } catch { - return; - } - if (manifest.schemaVersion !== 1 || manifest.apiPath !== api) return; + const loaded = await manifestReady; + if (!loaded) return; - const displayed = view || manifest.defaultView; - const order = manifest.viewOrder ?? Object.keys(manifest.views); + const displayed = view || loaded.defaultView; + const order = loaded.viewOrder ?? Object.keys(loaded.views); if (order.length < 2 || !order.includes(displayed)) return; const select = document.getElementById('framework-view-select'); const status = document.getElementById('framework-view-status'); - for (const id of order) select.add(new Option(frameworkName(manifest.views[id]), id)); + for (const id of order) select.add(new Option(frameworkName(loaded.views[id]), id)); select.value = displayed; container.hidden = false; @@ -123,7 +195,7 @@ } function showFallback(requested, selected) { - status.textContent = `This API is not documented for ${frameworkName(manifest.views[requested])}. Showing ${frameworkName(manifest.views[selected])}.`; + status.textContent = `This API is not documented for ${frameworkName(loaded.views[requested])}. Showing ${frameworkName(loaded.views[selected])}.`; } select.addEventListener('change', async () => { @@ -136,10 +208,9 @@ const page = new URL(location.href); const anchor = findAnchor(page.hash.slice(1)); const uid = anchor?.dataset.uid || article.dataset.uid; - const index = order.indexOf(requested); - const candidates = new Set([requested, ...order.slice(0, index).reverse(), displayed, ...order.slice(index + 1)]); + const candidates = new Set([requested, ...order]); for (const candidate of candidates) { - const target = await findUid(manifest.views[candidate], uid); + const target = await findUid(loaded.views[candidate], uid); if (!target) continue; if (candidate === displayed) { diff --git a/tests/Test-DocfxContainer.ps1 b/tests/Test-DocfxContainer.ps1 index 668c5c4..9ecb1aa 100644 --- a/tests/Test-DocfxContainer.ps1 +++ b/tests/Test-DocfxContainer.ps1 @@ -142,7 +142,7 @@ try { if (Get-ChildItem -LiteralPath $destination -Filter 'build-*.log' -Recurse) { throw 'Ordinary multi-framework metadata generation unexpectedly triggered a recovery build.' } - foreach ($project in 'Runtime', 'Utilities') { + foreach ($project in 'Runtime', 'Utilities', 'ModernApi', 'StandardApi') { if (!(Test-Path -LiteralPath (Join-Path $fixture "$project/obj/project.assets.json") -PathType Leaf)) { throw "Packaged generator did not restore '$project'." } @@ -165,16 +165,27 @@ try { } $nginx = Get-Content -LiteralPath (Join-Path $destination 'nginx.conf') -Raw - if (-not $nginx.Contains('location ^~ /api/') -or $nginx -match '__(API|VIEWS|SEARCH)__') { + if (-not $nginx.Contains('location ^~ /api/') -or -not $nginx.Contains('location @framework_fallback') -or + $nginx -match '__(API|VIEWS|SEARCH|FALLBACK)__') { throw 'Generated NGINX configuration is incomplete or contains unsubstituted placeholders.' } $widget = 'api/runtime/FrameworkFixture.Runtime.Widget.html' $availability = @{ - $widget = @($expectedViews.Keys) - 'api/utilities/FrameworkFixture.Utilities.Utility.html' = @($expectedViews.Keys) + $widget = @($expectedViews.Keys) + 'api/utilities/FrameworkFixture.Utilities.Utility.html' = @($expectedViews.Keys) 'api/runtime/FrameworkFixture.Runtime.ModernFeature.html' = @('net-11.0', 'net-10.0') + 'api/runtime/FrameworkFixture.Runtime.StandardFeature.html' = @('netstandard-2.1', 'netstandard-2.0') 'api/runtime/FrameworkFixture.Runtime.LegacyFeature.html' = @('net48') + 'api/modern/FrameworkFixture.ModernApi.Endpoint.html' = @('net-11.0', 'net-10.0') + 'api/standard/FrameworkFixture.StandardApi.Adapter.html' = @('netstandard-2.1', 'netstandard-2.0') + } + foreach ($page in $availability.Keys) { + $relative = $page.Substring(4) + $actualSet = $manifest.availability.sets[$manifest.availability.pages[$relative]] + if (($actualSet -join ',') -cne ($availability[$page] -join ',')) { + throw "Unexpected manifest availability for '$page': $($actualSet -join ',')." + } } foreach ($view in $expectedViews.Keys) { $directory = $expectedViews[$view] diff --git a/tests/framework-view/Build-DocfxFrameworkViews.Tests.ps1 b/tests/framework-view/Build-DocfxFrameworkViews.Tests.ps1 index 2cf9b11..414c07e 100644 --- a/tests/framework-view/Build-DocfxFrameworkViews.Tests.ps1 +++ b/tests/framework-view/Build-DocfxFrameworkViews.Tests.ps1 @@ -143,7 +143,12 @@ switch ($args[0]) { It 'continues through rendering on ordinary warnings and skips metadata on a warm cache' { & $build -DocfxConfig $config -OutputRoot $output -MetadataCache $cache -MetadataCacheKey 'fixture' Test-Path -LiteralPath "$output/site/api/Library.html" | Should -BeTrue - (Get-Content -LiteralPath "$output/site/framework-views.json" -Raw | ConvertFrom-Json).defaultView | Should -BeExactly 'net-11.0' + $manifest = Get-Content -LiteralPath "$output/site/framework-views.json" -Raw | ConvertFrom-Json -AsHashtable + $manifest.defaultView | Should -BeExactly 'net-11.0' + $manifest.availability.sets[$manifest.availability.pages['Library.html']] | Should -BeExactly @('net-11.0', 'net-10.0') + $nginx = Get-Content -LiteralPath "$output/nginx.conf" -Raw + $nginx | Should -Not -Match '__(API|VIEWS|SEARCH|FALLBACK)__' + $nginx | Should -Match 'location @framework_fallback' @(Get-ChildItem -LiteralPath $cache -Filter '*.zip' -Recurse).Count | Should -Be 2 & $build -DocfxConfig $config -OutputRoot $output -MetadataCache $cache -MetadataCacheKey 'fixture' @(Select-String -LiteralPath "$fixture/docfx.log" -Pattern '^metadata .* --noRestore$').Count | Should -Be 2 diff --git a/tests/framework-view/FrameworkViewConventions.Tests.ps1 b/tests/framework-view/FrameworkViewConventions.Tests.ps1 index 9eddc9b..277f078 100644 --- a/tests/framework-view/FrameworkViewConventions.Tests.ps1 +++ b/tests/framework-view/FrameworkViewConventions.Tests.ps1 @@ -1,5 +1,6 @@ BeforeAll { . "$PSScriptRoot/../../framework-views/FrameworkViewConventions.ps1" + . "$PSScriptRoot/../../framework-views/DocfxMetadata.ps1" } Describe 'Framework view conventions' { @@ -92,3 +93,122 @@ Describe 'Output ownership and path isolation' { { Get-FrameworkOutputEntries $root.FullName '.owner' '.lock' } | Should -Throw '*contains a link*' } } + +Describe 'Page availability inventory, NGINX fallback rules and shared navigation TOC' { + It 'derives deterministic deduplicated page availability in framework precedence order' { + $site = (New-Item -ItemType Directory -Path "$TestDrive/avail-site").FullName + New-Item -ItemType Directory -Path "$site/api/dotnet", "$site/api/aspnet", "$site/_frameworks/net10/api/dotnet", "$site/_frameworks/net10/api/aspnet", "$site/_frameworks/netstandard2.0/api/dotnet", "$site/_frameworks/net48/api/legacy" -Force | Out-Null + Set-Content -LiteralPath "$site/api/dotnet/Common.html" 'net11' + Set-Content -LiteralPath "$site/api/aspnet/Endpoint.html" 'net11' + Set-Content -LiteralPath "$site/api/aspnet/toc.json" '{}' + Set-Content -LiteralPath "$site/_frameworks/net10/api/dotnet/Common.html" 'net10' + Set-Content -LiteralPath "$site/_frameworks/net10/api/aspnet/Endpoint.html" 'net10' + Set-Content -LiteralPath "$site/_frameworks/netstandard2.0/api/dotnet/Common.html" 'ns20' + Set-Content -LiteralPath "$site/_frameworks/net48/api/legacy/Legacy.html" 'net48' + + $views = [ordered]@{ + 'net-11.0' = [ordered]@{ directory = 'net11' } + 'net-10.0' = [ordered]@{ directory = 'net10' } + 'netstandard-2.1' = [ordered]@{ directory = 'netstandard2.1' } + 'netstandard-2.0' = [ordered]@{ directory = 'netstandard2.0' } + 'net48' = [ordered]@{ directory = 'net48' } + } + + $availability = Get-FrameworkPageAvailability $site 'api' 'net-11.0' $views + @($availability.pages.Keys) | Should -BeExactly @('aspnet/Endpoint.html', 'dotnet/Common.html', 'legacy/Legacy.html') + $availability.sets[$availability.pages['aspnet/Endpoint.html']] | Should -BeExactly @('net-11.0', 'net-10.0') + $availability.sets[$availability.pages['dotnet/Common.html']] | Should -BeExactly @('net-11.0', 'net-10.0', 'netstandard-2.0') + $availability.sets[$availability.pages['legacy/Legacy.html']] | Should -BeExactly @('net48') + $availability.pages.Contains('aspnet/toc.json') | Should -BeFalse + + # Duplicate availability set reuses the same set index. + Set-Content -LiteralPath "$site/api/aspnet/Second.html" 'net11' + Set-Content -LiteralPath "$site/_frameworks/net10/api/aspnet/Second.html" 'net10' + $updated = Get-FrameworkPageAvailability $site 'api' 'net-11.0' $views + $updated.pages['aspnet/Second.html'] | Should -Be $updated.pages['aspnet/Endpoint.html'] + $updated.sets.Count | Should -Be 3 + } + + It 'generates ordered NGINX fallback rules for default and non-default views' { + $views = [ordered]@{ + 'net-11.0' = [ordered]@{ directory = 'net11' } + 'netstandard-2.0' = [ordered]@{ directory = 'netstandard2.0' } + } + $rules = @(Get-FrameworkNginxFallbackRules 'net-11.0' $views) + $rules.Count | Should -Be 2 + $rules[0] | Should -BeExactly ' if (-f $document_root$framework_fallback_target) { return 302 $uri?${framework_query_prefix}view=net-11.0; }' + $rules[1] | Should -BeExactly ' if (-f $document_root/_frameworks/netstandard2.0$framework_fallback_target) { return 302 $uri?${framework_query_prefix}view=netstandard-2.0; }' + } + + It 'normalizes API page paths and ignores non-API or empty hrefs' { + Resolve-FrameworkApiRelativePage '' 'api/' | Should -BeNullOrEmpty + Resolve-FrameworkApiRelativePage 'index.html' 'api/' | Should -BeNullOrEmpty + Resolve-FrameworkApiRelativePage '/api/dotnet/Common.html?view=net-10.0#top' 'api/' | Should -BeExactly 'dotnet/Common.html' + Resolve-FrameworkApiRelativePage 'api/legacy/' 'api/' | Should -BeExactly 'legacy/index.html' + Resolve-FrameworkApiRelativePage 'api/' 'api/' | Should -BeExactly 'index.html' + } + + It 'merges unresolved non-default API navigation entries including nested items and handles edge cases' { + $work = (New-Item -ItemType Directory -Path "$TestDrive/toc-merge").FullName + $site = (New-Item -ItemType Directory -Path "$work/site").FullName + $views = [ordered]@{ + 'net-11.0' = [ordered]@{ directory = 'net11' } + 'net-10.0' = [ordered]@{ directory = 'net10' } + 'netstandard-2.0' = [ordered]@{ directory = 'netstandard2.0' } + 'net48' = [ordered]@{ directory = 'net48' } + } + $availability = [ordered]@{ + sets = @(, @('net-11.0'), @('netstandard-2.0', 'net48')) + pages = [ordered]@{ + 'dotnet/Common.html' = 0 + 'legacy/Legacy.html' = 1 + 'nested/Nested.html' = 1 + } + } + + # Missing toc.json is a no-op. + Merge-SharedNavigationToc $site $work '_site' 'api' 'net-11.0' $views $availability + Merge-NavigationTocItems $null @() 'api/' $availability | Should -BeFalse + + # toc.json without items is a no-op. + Write-Json "$site/toc.json" @{ memberLayout = 'SamePage' } + Merge-SharedNavigationToc $site $work '_site' 'api' 'net-11.0' $views $availability + + # toc.json with no candidate toc.json files is a no-op. + Write-Json "$site/toc.json" @{ items = @(@{ name = 'Concept'; href = 'index.html' }) } + Merge-SharedNavigationToc $site $work '_site' 'api' 'net-11.0' $views $availability + + # Candidate toc.json exists with empty/shorter items and nested items. + New-Item -ItemType Directory -Path "$work/net10/_site", "$work/netstandard2.0/_site", "$work/net48/_site" -Force | Out-Null + Write-Json "$work/net10/_site/toc.json" @{ items = @(@{ name = 'Concept'; href = 'index.html' }) } + Write-Json "$work/netstandard2.0/_site/toc.json" @{ + items = @( + @{ name = 'Concept'; href = 'index.html' } + @{ name = '.NET API'; href = 'api/dotnet/Common.html' } + @{ name = 'Legacy API'; href = 'api/legacy/Legacy.html'; topicHref = 'api/legacy/Legacy.html'; tocHref = 'api/legacy/toc.html' } + @{ name = 'Group'; items = @(@{ name = 'Nested'; href = 'api/nested/Nested.html' }) } + ) + } + Write-Json "$work/net48/_site/toc.json" @{ memberLayout = 'SamePage' } + Write-Json "$site/toc.json" @{ + items = @( + @{ name = 'Concept'; href = 'index.html' } + @{ name = '.NET API'; href = 'api/dotnet/Common.html' } + @{ name = 'Legacy API'; href = 'api/legacy/Legacy.yml' } + @{ name = 'Group'; items = @(@{ name = 'Nested'; href = 'api/nested/Nested.yml' }) } + ) + } + + Merge-SharedNavigationToc $site $work '_site' 'api' 'net-11.0' $views $availability + $merged = Read-Json "$site/toc.json" + $merged.items[2].href | Should -BeExactly 'api/legacy/Legacy.html' + $merged.items[2].topicHref | Should -BeExactly 'api/legacy/Legacy.html' + $merged.items[2].tocHref | Should -BeExactly 'api/legacy/toc.html' + $merged.items[3].items[0].href | Should -BeExactly 'api/nested/Nested.html' + + # Re-running when everything is already resolved is an unchanged no-op. + $before = Get-Content -LiteralPath "$site/toc.json" -Raw + Merge-SharedNavigationToc $site $work '_site' 'api' 'net-11.0' $views $availability + Get-Content -LiteralPath "$site/toc.json" -Raw | Should -BeExactly $before + } +} diff --git a/tests/framework-view/README.md b/tests/framework-view/README.md index e81e48f..1797055 100644 --- a/tests/framework-view/README.md +++ b/tests/framework-view/README.md @@ -29,13 +29,13 @@ These exercise glob exclusions, nested metadata destinations, per-view project a ## Packaged builder and browser regression -Two fixture projects document `/api/runtime/` and `/api/utilities/`. Conditional APIs distinguish five framework views. The container test builds the image locally and runs the packaged generator with a clean mounted copy of the fixture. It checks PowerShell, both installed SDKs, DocFX, restore assets, the rendered views and their native xrefs, search indexes, and NGINX routes. The container-only check requires Docker in Linux-container mode. +Four fixture projects document `/api/runtime/`, `/api/utilities/`, `/api/modern/` (`.NET 11` and `.NET 10` only), and `/api/standard/` (`.NET Standard 2.1` and `.NET Standard 2.0` only), alongside conditional per-type APIs across five framework views. The container test builds the image locally and runs the packaged generator with a clean mounted copy of the fixture. It checks PowerShell, both installed SDKs, DocFX, restore assets, the rendered views and their native xrefs, search indexes, page availability manifest, and NGINX fallback routes. The container-only check requires Docker in Linux-container mode. ```powershell pwsh -NoProfile -File tests/framework-view/Test-FrameworkView.ps1 -ContainerOnly ``` -The complete suite also runs the generator natively and compares the runtime manifest and routing with the container build. It serves the native output and an ordinary single-framework site with the shared NGINX Dockerfile. The browser checks cover the selector, UID and fragment resolution, fallback, direct URLs, navigation, search, and mobile keyboard operation. +The complete suite also runs the generator natively and compares the runtime manifest and routing with the container build. It serves the native output and an ordinary single-framework site with the shared NGINX Dockerfile. The browser and HTTP checks cover the selector, UID and fragment resolution, unified default and non-default fallback precedence, global navigation, TOCs, breadcrumbs, cross-references, ordinary internal API hyperlinks, new-tab opening without click interception, JavaScript-disabled navigation, browser history, query parameter and fragment preservation, genuine 404s, invalid-view 400s, strict TOC/xref/search isolation, and mobile keyboard operation. ```powershell Push-Location tests/framework-view @@ -47,9 +47,9 @@ pwsh -File tests/framework-view/Test-FrameworkView.ps1 On Linux, install Chromium's system dependencies with `npx playwright install --with-deps chromium` if needed. Use `-SkipImageBuild -BuilderImage ` to test an existing builder image. For CI-aligned native builder image validation (including OCI labels, architecture, SDKs, PowerShell 7, complete `/opt/docfx/framework-views` distribution, multi-framework build, and single-framework build), run `pwsh -NoProfile -File tests/Test-DocfxContainer.ps1 -Image -Platform linux/amd64`. Official production publication uses the build-once GitHub Actions release and deployment lifecycle described in [CI/CD release and deployment lifecycle](../../README.md#cicd-release-and-deployment-lifecycle). -## Cuemon.Kernel and Cuemon.IO +## Cuemon.Kernel, Cuemon.IO and Cuemon.AspNetCore -The test uses the authored Cuemon project mappings, filter, overwrites, template, and run actions from the [fixture revision](https://github.com/codebeltnet/cuemon/tree/53875b1bbb778067a0a029b87861efdb0b78a8b5). It stages a two-project configuration in the consumer checkout and exercises the generator's cross-target reference recovery. Run on Windows or Linux with Git and the native prerequisites above. +The test uses the authored Cuemon project mappings, filter, overwrites, template, and run actions from the [fixture revision](https://github.com/codebeltnet/cuemon/tree/53875b1bbb778067a0a029b87861efdb0b78a8b5). It stages a multi-section configuration (`api/dotnet` for `Cuemon.Kernel` and `Cuemon.IO`; `api/aspnet` for `Cuemon.AspNetCore`) in the consumer checkout, exercising cross-target reference recovery and reproducing the reported `.NET Standard 2.0` -> `ASP.NET Core API` navigation scenario using real Cuemon metadata. Run on Windows or Linux with Git and the native prerequisites above. ```powershell $scratch = Join-Path ([IO.Path]::GetTempPath()) "docfx-cuemon-$([guid]::NewGuid().ToString('N'))" @@ -61,4 +61,4 @@ pwsh -NoProfile -File tests/framework-view/cuemon/Build-CuemonFixture.ps1 -Consu pwsh -NoProfile -File tests/framework-view/cuemon/Test-CuemonFrameworkViews.ps1 -Workspace $output ``` -The acceptance test checks the native xref inventory against every served API and fragment, framework-specific TOCs and search, overload and inheritance differences, source and run-action links, overwrite examples, and HTTP caching. It expects 557, 557, 76 and 548 metadata UIDs in framework order. To use the builder image, run the entire fixture build in the container with the test scripts and a writable fixture checkout mounted. Pass `-Origin ` to the acceptance test to check an already running server. +The acceptance test checks the native xref inventory against every served API and fragment, page availability metadata, HTTP 302 destination-aware fallback (both default `.NET 11` fallback for `Cuemon.AspNetCore` / `BufferWriterOptions` / `Validator` and non-default `.NET Standard 2.0` fallback for `CallerArgumentExpressionAttribute`), strict TOC/xref/search isolation, overload and inheritance differences, source and run-action links, overwrite examples, and HTTP caching. It expects 937 (557 dotnet + 380 aspnet), 937 (557 dotnet + 380 aspnet), 76 and 548 metadata UIDs in framework order. To use the builder image, run the entire fixture build in the container with the test scripts and a writable fixture checkout mounted. Pass `-Origin ` to the acceptance test to check an already running server. diff --git a/tests/framework-view/Test-FrameworkView.ps1 b/tests/framework-view/Test-FrameworkView.ps1 index 6d927ef..d311aa7 100644 --- a/tests/framework-view/Test-FrameworkView.ps1 +++ b/tests/framework-view/Test-FrameworkView.ps1 @@ -46,7 +46,7 @@ function Test-PackagedGenerator { throw 'Ordinary metadata generation ran a recovery compilation.' } - foreach ($project in 'Runtime', 'Utilities') { + foreach ($project in 'Runtime', 'Utilities', 'ModernApi', 'StandardApi') { if (!(Test-Path -LiteralPath "$fixture/$project/obj/project.assets.json" -PathType Leaf)) { throw "The packaged generator did not restore '$project'." } @@ -65,15 +65,26 @@ function Test-PackagedGenerator { throw 'The packaged generator did not discover and package the expected views.' } $nginx = Get-Content -LiteralPath "$destination/nginx.conf" -Raw - if (!$nginx.Contains('location ^~ /api/') -or $nginx -match '__(API|VIEWS|SEARCH)__') { - throw 'The packaged generator did not configure the API routes.' + if (!$nginx.Contains('location ^~ /api/') -or !$nginx.Contains('location @framework_fallback') -or + $nginx -match '__(API|VIEWS|SEARCH|FALLBACK)__') { + throw 'The packaged generator did not configure the API and fallback routes.' } $widget = 'api/runtime/FrameworkFixture.Runtime.Widget.html' $availability = @{ $widget = $expectedViews.Keys 'api/utilities/FrameworkFixture.Utilities.Utility.html' = $expectedViews.Keys 'api/runtime/FrameworkFixture.Runtime.ModernFeature.html' = 'net-11.0', 'net-10.0' + 'api/runtime/FrameworkFixture.Runtime.StandardFeature.html' = 'netstandard-2.1', 'netstandard-2.0' 'api/runtime/FrameworkFixture.Runtime.LegacyFeature.html' = 'net48' + 'api/modern/FrameworkFixture.ModernApi.Endpoint.html' = 'net-11.0', 'net-10.0' + 'api/standard/FrameworkFixture.StandardApi.Adapter.html' = 'netstandard-2.1', 'netstandard-2.0' + } + foreach ($page in $availability.Keys) { + $relative = $page.Substring(4) + $actualSet = $manifest.availability.sets[$manifest.availability.pages[$relative]] + if (($actualSet -join ',') -cne (@($availability[$page]) -join ',')) { + throw "Unexpected manifest availability for '$page': $($actualSet -join ',')." + } } foreach ($view in $expectedViews.Keys) { $directory = $expectedViews[$view] diff --git a/tests/framework-view/Test-FrameworkViews.ps1 b/tests/framework-view/Test-FrameworkViews.ps1 index d86fdcc..20098d3 100644 --- a/tests/framework-view/Test-FrameworkViews.ps1 +++ b/tests/framework-view/Test-FrameworkViews.ps1 @@ -131,10 +131,15 @@ if ($ProjectSdk8 -and [version](Get-Content -LiteralPath "$fresh/resolver-sdk.lo throw 'The resolver did not select a modern SDK independently of the project pin.' } $site = "$fresh/site" -$manifest = Get-Content "$site/framework-views.json" -Raw | ConvertFrom-Json +$manifest = Get-Content "$site/framework-views.json" -Raw | ConvertFrom-Json -AsHashtable if (($manifest.viewOrder -join ',') -cne "$defaultView,$otherView" -or $manifest.defaultView -cne $defaultView -or $manifest.apiPath -cne '/reference/') { throw 'The generated manifest does not reflect the inferred API root and framework precedence.' } +if ($manifest.availability.sets[$manifest.availability.pages['runtime/FrameworkFixture.Modern.html']] -join ',' -cne $defaultView -or + $manifest.availability.sets[$manifest.availability.pages['legacy/FrameworkFixture.Compatibility.Legacy.html']] -join ',' -cne $otherView -or + $manifest.availability.sets[$manifest.availability.pages['runtime/FrameworkFixture.Common.html']] -join ',' -cne "$defaultView,$otherView") { + throw 'The generated page availability inventory does not reflect the native DocFX output.' +} foreach ($assembly in @( @{ path = "$root/src/Runtime/bin/Release/$defaultTfm/Runtime.dll"; identity = 'Runtime, Version=3.0.0.0, Culture=neutral, PublicKeyToken=null' } @{ path = "$root/dependencies/Bridge/bin/Release/netstandard2.0/Bridge.dll"; identity = 'Bridge, Version=7.1.0.0, Culture=neutral, PublicKeyToken=null' } @@ -215,18 +220,54 @@ if ($TestRouting) { @{ path = "/reference/runtime/index.html?view=$otherView"; status = 200; body = 'other API index' } @{ path = "/reference/runtime/FrameworkFixture.Common.html?view=$otherView"; status = 200; body = 'FrameworkFixture' } @{ path = '/reference/runtime/?view=unknown'; status = 400; body = 'Unknown documentation view.' } - @{ path = "/reference/runtime/FrameworkFixture.Modern.html?view=$otherView"; status = 404 } - @{ path = '/reference/legacy/'; status = 404 } + @{ path = "/reference/runtime/FrameworkFixture.Modern.html?view=$otherView"; status = 302; location = "/reference/runtime/FrameworkFixture.Modern.html?view=$defaultView" } + @{ path = "/reference/runtime/FrameworkFixture.Modern.html?tag=a&view=$otherView&tag=b"; status = 302; location = "/reference/runtime/FrameworkFixture.Modern.html?tag=a&tag=b&view=$defaultView" } + @{ path = "/reference/runtime/FrameworkFixture.Modern.html?tag=a&VIEW=$otherView&view=$otherView&tag=b"; status = 302; location = "/reference/runtime/FrameworkFixture.Modern.html?tag=a&tag=b&view=$defaultView" } + @{ path = "/reference/runtime/FrameworkFixture.Modern.html?view=$otherView&view=$otherView&view=$otherView"; status = 400; body = 'Unknown documentation view.' } + @{ path = '/reference/legacy/'; status = 302; location = "/reference/legacy/?view=$otherView" } @{ path = "/reference/legacy/?view=$otherView"; status = 200; body = 'other legacy index' } + @{ path = "/reference/legacy/FrameworkFixture.Compatibility.Legacy.html?view=$defaultView"; status = 302; location = "/reference/legacy/FrameworkFixture.Compatibility.Legacy.html?view=$otherView" } + @{ path = "/reference/runtime/DoesNotExist.html?view=$otherView"; status = 404 } + @{ path = '/reference/legacy/toc.json'; status = 404 } + @{ path = '/reference/runtime/missing.png'; status = 404 } ) - foreach ($expected in $responses) { - $result = Invoke-WebRequest "http://$endpoint$($expected.path)" -SkipHttpErrorCheck -MaximumRedirection 0 - $body = if ($result.Content -is [byte[]]) { [Text.Encoding]::UTF8.GetString($result.Content) } else { $result.Content } - $expectedBody = $expected['body'] - if ($result.StatusCode -ne $expected.status -or ($expectedBody -and !$body.Contains($expectedBody)) -or - $result.Headers['Cache-Control'] -notlike '*no-store*' -or $result.Headers['ETag']) { - throw "Unexpected routing or caching for '$($expected.path)' (HTTP $($result.StatusCode))." + $handler = [Net.Http.HttpClientHandler]::new() + $handler.AllowAutoRedirect = $false + $client = [Net.Http.HttpClient]::new($handler) + $client.Timeout = [TimeSpan]::FromSeconds(10) + try { + $baseUri = [uri]"http://$endpoint" + foreach ($expected in $responses) { + $response = $client.GetAsync([uri]::new($baseUri, $expected.path)).GetAwaiter().GetResult() + try { + $statusCode = [int]$response.StatusCode + $body = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult() + $expectedBody = $expected['body'] + $expectedLocation = $expected['location'] + $actualLocation = if ($response.Headers.Location) { $response.Headers.Location.OriginalString } + $cacheControl = if ($response.Headers.CacheControl) { $response.Headers.CacheControl.ToString() } else { '' } + if ($statusCode -ne $expected.status -or ($expectedBody -and !$body.Contains($expectedBody)) -or + ($expectedLocation -and $actualLocation -cne $expectedLocation) -or + (!$expectedLocation -and $actualLocation) -or + $cacheControl -notlike '*no-store*' -or $response.Headers.ETag) { + throw "Unexpected routing or caching for '$($expected.path)' (HTTP $statusCode, Location '$actualLocation')." + } + } finally { + $response.Dispose() + } + if ($expectedLocation) { + $follow = $client.GetAsync([uri]::new($baseUri, $expectedLocation)).GetAwaiter().GetResult() + try { + if ([int]$follow.StatusCode -ne 200) { + throw "Fallback destination '$expectedLocation' returned HTTP $([int]$follow.StatusCode)." + } + } finally { + $follow.Dispose() + } + } } + } finally { + $client.Dispose() } } finally { & docker stop $container | Out-Null diff --git a/tests/framework-view/cuemon/Build-CuemonFixture.ps1 b/tests/framework-view/cuemon/Build-CuemonFixture.ps1 index 9cd2501..ad51be2 100644 --- a/tests/framework-view/cuemon/Build-CuemonFixture.ps1 +++ b/tests/framework-view/cuemon/Build-CuemonFixture.ps1 @@ -12,34 +12,48 @@ $ErrorActionPreference = 'Stop' $consumer = (Resolve-Path -LiteralPath $ConsumerRoot).Path $source = "$consumer/.docfx" -# Use the authored inputs for the two-project fixture. The shared script owns discovery and generation. +# Use the authored inputs for the multi-section fixture (Cuemon.Kernel, Cuemon.IO and Cuemon.AspNetCore). +# The shared generator owns discovery, availability inventory, navigation and routing. $config = Get-Content -LiteralPath "$source/docfx.json" -Raw | ConvertFrom-Json -AsHashtable -$group = @($config.metadata | Where-Object dest -CEQ 'api/dotnet') -if ($group.Count -ne 1 -or $group[0].src.Count -ne 1) { throw 'Expected one api/dotnet metadata group with one source mapping.' } -$config.metadata = $group -$mapping = $group[0].src[0] -$mapping.src = [IO.Path]::GetFullPath($mapping.src, $source) -$mapping.files = @($mapping.files | Where-Object { $_ -cmatch '^Cuemon\.(Kernel|IO)/' }) -if ($mapping.files.Count -ne 2) { throw 'Expected the authored Cuemon.Kernel and Cuemon.IO project mappings.' } +$dotnetGroup = @($config.metadata | Where-Object dest -CEQ 'api/dotnet') +$aspnetGroup = @($config.metadata | Where-Object dest -CEQ 'api/aspnet') +if ($dotnetGroup.Count -ne 1 -or $dotnetGroup[0].src.Count -ne 1) { throw 'Expected one api/dotnet metadata group with one source mapping.' } +if ($aspnetGroup.Count -ne 1 -or $aspnetGroup[0].src.Count -ne 1) { throw 'Expected one api/aspnet metadata group with one source mapping.' } + +$dotnetMapping = $dotnetGroup[0].src[0] +$dotnetMapping.src = [IO.Path]::GetFullPath($dotnetMapping.src, $source) +$dotnetMapping.files = @($dotnetMapping.files | Where-Object { $_ -cmatch '^Cuemon\.(Kernel|IO)/' }) +if ($dotnetMapping.files.Count -ne 2) { throw 'Expected the authored Cuemon.Kernel and Cuemon.IO project mappings.' } + +$aspnetMapping = $aspnetGroup[0].src[0] +$aspnetMapping.src = [IO.Path]::GetFullPath($aspnetMapping.src, $source) +$aspnetMapping.files = @($aspnetMapping.files | Where-Object { $_ -cmatch '^Cuemon\.AspNetCore/' }) +if ($aspnetMapping.files.Count -ne 1) { throw 'Expected the authored Cuemon.AspNetCore project mapping.' } + +$config.metadata = @($dotnetGroup[0], $aspnetGroup[0]) if (!(Test-Path -LiteralPath "$consumer/cuemon.snk" -PathType Leaf)) { - $group[0].properties = @{ SkipSignAssembly = 'true' } + foreach ($group in $config.metadata) { + $group.properties = @{ SkipSignAssembly = 'true' } + } } $config.build.Remove('sitemap') $config.build.Remove('xref') $config.build.globalMetadata.Remove('_googleAnalyticsTagId') -$config.build.content = @(@{ files = @('api/dotnet/**/*.yml', 'index.md', 'toc.yml') }) +$config.build.content = @(@{ files = @('api/**/*.yml', 'index.md', 'toc.yml') }) $workspace = Join-Path $consumer "cuemon-docfx-input-$([guid]::NewGuid().ToString('N'))" $inputRoot = Join-Path $workspace 'input' New-Item -ItemType Directory -Path "$inputRoot/api" -Force | Out-Null try { - Copy-Item -LiteralPath "$source/includes", "$source/images", "$source/templates", "$source/index.md", "$source/$($group[0].filter)" -Destination $inputRoot -Recurse + Copy-Item -LiteralPath "$source/includes", "$source/images", "$source/templates", "$source/index.md", "$source/$($dotnetGroup[0].filter)" -Destination $inputRoot -Recurse Copy-Item -LiteralPath "$source/api/namespaces", "$source/api/types" -Destination "$inputRoot/api" -Recurse @' - name: Concept Reference href: index.md - name: .NET API - href: api/dotnet/Cuemon.IO.yml + href: api/dotnet/Cuemon.html +- name: ASP.NET Core API + href: api/aspnet/Cuemon.AspNetCore.html '@ | Set-Content -LiteralPath "$inputRoot/toc.yml" ConvertTo-Json -InputObject $config -Depth 100 | Set-Content -LiteralPath "$inputRoot/docfx.json" & "$source/BuildRunActions.ps1" -OutputRoot "$inputRoot/run-actions" diff --git a/tests/framework-view/cuemon/Test-CuemonFrameworkViews.ps1 b/tests/framework-view/cuemon/Test-CuemonFrameworkViews.ps1 index 5155fbf..720ae2b 100644 --- a/tests/framework-view/cuemon/Test-CuemonFrameworkViews.ps1 +++ b/tests/framework-view/cuemon/Test-CuemonFrameworkViews.ps1 @@ -14,7 +14,9 @@ $site = "$workspace/site" $legacy = 'System.Runtime.CompilerServices.CallerArgumentExpressionAttribute' $buffer = 'Cuemon.IO.BufferWriterOptions' $factory = 'Cuemon.IO.StreamFactory' -$baselineUids = @{ 'net11.0' = 557; 'net10.0' = 557; 'netstandard2.1' = 76; 'netstandard2.0' = 548 } +$aspnetNamespace = 'Cuemon.AspNetCore' +$dotnetBaselineUids = @{ 'net11.0' = 557; 'net10.0' = 557; 'netstandard2.1' = 76; 'netstandard2.0' = 548 } +$aspnetBaselineUids = @{ 'net11.0' = 380; 'net10.0' = 380; 'netstandard2.1' = 0; 'netstandard2.0' = 0 } function Assert-True([bool] $Condition, [string] $Message) { if (!$Condition) { throw $Message } @@ -61,10 +63,16 @@ function Compare-Trees([string] $Left, [string] $Right) { Assert-True (!$differences.Count) "Different files between $Left and $Right ($($differences.Count)): $($differences | Select-Object -First 15)" } -function Get-Page([string] $Path, [int] $Status = 200, [string] $Mime) { +function Get-Page([string] $Path, [int] $Status = 200, [string] $Mime, [string] $Location) { $response = $client.GetAsync([uri]::new($baseUri, $Path)).GetAwaiter().GetResult() try { Assert-True ([int]$response.StatusCode -eq $Status) "$Path returned $([int]$response.StatusCode), expected $Status." + $actualLocation = if ($response.Headers.Location) { $response.Headers.Location.OriginalString } + if ($Location) { + Assert-True ($actualLocation -ceq $Location) "$Path redirected to '$actualLocation', expected '$Location'." + } else { + Assert-True (!$actualLocation) "$Path unexpectedly redirected to '$actualLocation'." + } if ($Mime) { Assert-True ($response.Content.Headers.ContentType.MediaType -match $Mime) "$Path has unexpected content type." } @@ -93,7 +101,12 @@ function Get-Xrefs([string] $Yaml, [string] $Api) { } $manifest = Read-Json "$site/framework-views.json" +Assert-True ($manifest.apiPath -ceq '/api/') "Unexpected API root '$($manifest.apiPath)'; expected '/api/'." Assert-True (($manifest.viewOrder -join ',') -ceq 'net-11.0,net-10.0,netstandard-2.1,netstandard-2.0') 'Unexpected framework views or order.' +Assert-True (($manifest.availability.sets[$manifest.availability.pages['aspnet/Cuemon.AspNetCore.html']] -join ',') -ceq 'net-11.0,net-10.0') 'Unexpected availability for aspnet/Cuemon.AspNetCore.html.' +Assert-True (($manifest.availability.sets[$manifest.availability.pages['dotnet/Cuemon.html']] -join ',') -ceq 'net-11.0,net-10.0,netstandard-2.0') 'Unexpected availability for dotnet/Cuemon.html.' +Assert-True (($manifest.availability.sets[$manifest.availability.pages["dotnet/$legacy.html"]] -join ',') -ceq 'netstandard-2.0') "Unexpected availability for dotnet/$legacy.html." +Assert-True (($manifest.availability.sets[$manifest.availability.pages["dotnet/$buffer.html"]] -join ',') -ceq 'net-11.0,net-10.0,netstandard-2.1') "Unexpected availability for dotnet/$buffer.html." if ($CompareWorkspace) { Compare-Trees $site "$CompareWorkspace/site" foreach ($entry in $manifest.views.Values) { @@ -129,11 +142,15 @@ try { } $api = $manifest.apiPath - $factoryPath = "$api$factory.html" + $dotnetApi = '/api/dotnet/' + $aspnetApi = '/api/aspnet/' + $factoryPath = "$dotnetApi$factory.html" + $aspnetPath = "$aspnetApi$aspnetNamespace.html" $defaultHtml = Get-Page $factoryPath 200 'text/html' Assert-True ($defaultHtml -ceq (Get-Page "$($factoryPath)?view=$($manifest.defaultView)" 200 'text/html')) 'Implicit and explicit default differ.' Get-Page "$($factoryPath)?view=unknown" 400 | Out-Null Get-Page "$($factoryPath)?view=$($manifest.defaultView.ToUpperInvariant())" 400 | Out-Null + Get-Page "$($aspnetPath)?view=unknown" 400 | Out-Null Get-Page '/index.html?view=unknown' 200 'text/html' | Out-Null Get-Page '/public/docfx.min.css?view=unknown' 200 'text/css' | Out-Null Get-Page '/public/docfx.min.js' 200 'javascript' | Out-Null @@ -144,15 +161,45 @@ try { Assert-True ($fontResponse.IsSuccessStatusCode -and $fontResponse.Headers.CacheControl.ToString().Contains('immutable')) 'Fingerprinted font caching policy changed.' } finally { $fontResponse.Dispose() } + # Reported Cuemon navigation scenario and destination-aware server-side fallback checks + Get-Page '/api/dotnet/Cuemon.html?view=netstandard-2.0' 200 'text/html' | Out-Null + Get-Page "$($aspnetPath)?view=netstandard-2.0" 302 $null "$($aspnetPath)?view=net-11.0" | Out-Null + Get-Page "$($aspnetPath)?view=netstandard-2.1" 302 $null "$($aspnetPath)?view=net-11.0" | Out-Null + Get-Page "$($aspnetPath)?tag=a&view=netstandard-2.0&tag=b" 302 $null "$($aspnetPath)?tag=a&tag=b&view=net-11.0" | Out-Null + $aspnetDefault = Get-Page "$($aspnetPath)?view=net-11.0" 200 'text/html' + Assert-True ($aspnetDefault.Contains('Cuemon.AspNetCore')) 'Resolved Cuemon.AspNetCore page missing expected content.' + Get-Page "$($aspnetPath)?view=net-10.0" 200 'text/html' | Out-Null + Get-Page '/api/aspnet/DoesNotExist.html?view=netstandard-2.0' 404 | Out-Null + Get-Page '/api/aspnet/toc.json?view=netstandard-2.0' 404 | Out-Null + Get-Page "$dotnetApi$legacy.html" 302 $null "$dotnetApi$legacy.html?view=netstandard-2.0" | Out-Null + Get-Page "$dotnetApi$legacy.html?view=net-11.0" 302 $null "$dotnetApi$legacy.html?view=netstandard-2.0" | Out-Null + Get-Page "$dotnetApi$buffer.html?view=netstandard-2.0" 302 $null "$dotnetApi$buffer.html?view=net-11.0" | Out-Null + Get-Page "${dotnetApi}Cuemon.Validator.html?view=netstandard-2.1" 302 $null "${dotnetApi}Cuemon.Validator.html?view=net-11.0" | Out-Null + + $rootToc = Get-Page '/toc.json' 200 'application/json' + Assert-True ($rootToc.Contains('api/dotnet/Cuemon.html') -and $rootToc.Contains('api/aspnet/Cuemon.AspNetCore.html')) 'Root navigation TOC missing expected Cuemon API entries.' + foreach ($view in $manifest.views.Keys) { $entry = $manifest.views[$view] $stage = "$workspace/$($entry.directory)" - $inventory = Read-Json "$stage$($api).manifest" - Assert-True ($inventory.Count -eq $baselineUids[$entry.tfm]) "Unexpected baseline UID count for $view." + $dotnetInventory = Read-Json "$stage${dotnetApi}.manifest" + Assert-True ($dotnetInventory.Count -eq $dotnetBaselineUids[$entry.tfm]) "Unexpected api/dotnet baseline UID count for $view." + $hasAspNet = $entry.tfm -cin 'net11.0', 'net10.0' + $aspnetManifestPath = "$stage${aspnetApi}.manifest" + Assert-True ((Test-Path -LiteralPath $aspnetManifestPath -PathType Leaf) -eq $hasAspNet) "Unexpected api/aspnet manifest presence for $view." + $combinedUids = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) + $combinedUids.UnionWith([string[]]@($dotnetInventory.Keys)) + $aspnetCount = 0 + if ($hasAspNet) { + $aspnetInventory = Read-Json $aspnetManifestPath + Assert-True ($aspnetInventory.Count -eq $aspnetBaselineUids[$entry.tfm]) "Unexpected api/aspnet baseline UID count for $view ($($aspnetInventory.Count))." + $aspnetCount = $aspnetInventory.Count + $combinedUids.UnionWith([string[]]@($aspnetInventory.Keys)) + } $xref = Get-Xrefs (Get-Page $entry.xref) $api $renderedUids = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) $renderedUids.UnionWith([string[]]@($xref.Keys | Where-Object { !$_.EndsWith('*') })) - Assert-True ($renderedUids.SetEquals([string[]]@($inventory.Keys))) "$view served xrefs differ from the isolated DocFX inventory." + Assert-True ($renderedUids.SetEquals($combinedUids)) "$view served xrefs differ from the isolated DocFX inventory." $pages = @{} foreach ($uid in $xref.Keys) { $path, $anchor = $xref[$uid].Split('#', 2) @@ -171,11 +218,19 @@ try { Get-Page $runAction.AbsolutePath | Out-Null $isLegacy = $entry.tfm -ceq 'netstandard2.0' - $toc = Get-Page "$($api)toc.json?view=$view" 200 'application/json' + $toc = Get-Page "$($dotnetApi)toc.json?view=$view" 200 'application/json' + if ($hasAspNet) { + $aspnetToc = Get-Page "$($aspnetApi)toc.json?view=$view" 200 'application/json' + Assert-True ($aspnetToc.Contains("""topicUid"":""$aspnetNamespace""")) "Missing $aspnetNamespace in api/aspnet TOC for $view." + } else { + Get-Page "$($aspnetApi)toc.json?view=$view" 404 | Out-Null + } $index = Get-Page "/_framework-search/$($entry.directory)/index.json" 200 'application/json' | ConvertFrom-Json -AsHashtable foreach ($path in $index.Keys) { if (("/$path").StartsWith($api) -and !$pages.ContainsKey($path)) { throw "Search indexes unavailable page $path in $view." } } + Assert-True ($xref.ContainsKey($aspnetNamespace) -eq $hasAspNet) "Wrong xref availability for $aspnetNamespace in $view." + Assert-True ($index.Contains("api/aspnet/$aspnetNamespace.html") -eq $hasAspNet) "Wrong search availability for $aspnetNamespace in $view." $overloads = @($xref.Keys | Where-Object { $_.StartsWith("$factory.Create") -and $_.Contains('System.Buffers.IBufferWriter{System.Byte}') }) $expectedCount = if ($isLegacy) { 0 } else { 6 } Assert-True ($overloads.Count -eq $expectedCount) "Wrong buffer writer overload count in $view." @@ -198,12 +253,16 @@ try { $buffer { !$isLegacy } default { $entry.tfm -cne 'netstandard2.1' } } - $path = "$($api.TrimStart('/'))$type.html" + $expectedFallback = switch ($type) { + $legacy { 'netstandard-2.0' } + default { 'net-11.0' } + } + $path = "$($dotnetApi.TrimStart('/'))$type.html" Assert-True ($xref.ContainsKey($type) -eq $expected) "Wrong xref availability for $type in $view." Assert-True ($toc.Contains("""topicUid"":""$type""") -eq $expected) "Wrong TOC availability for $type in $view." Assert-True ($index.Contains($path) -eq $expected) "Wrong search availability for $type in $view." if (!$expected) { - Get-Page "/$($path)?view=$view" 404 | Out-Null + Get-Page "/$($path)?view=$view" 302 $null "/$($path)?view=$expectedFallback" | Out-Null continue } Assert-True ($pages[$path] -match 'github\.com/codebeltnet/cuemon/blob/[^"]+\.cs/#L\d+') "Missing source link for $type in $view." @@ -215,7 +274,7 @@ try { Assert-True ($html -match '(?s)

Examples

.*?
]*>\s*\S') "Missing authored example for $($file.BaseName) in $view."
         }
         Get-Page "/_frameworks/$($entry.directory)$factoryPath" 404 | Out-Null
-        Write-Host "$view passed $($inventory.Count) UID, anchor, TOC and search checks across $($pages.Count) served API pages."
+        Write-Host "$view passed $($combinedUids.Count) UID ($($dotnetInventory.Count) dotnet + $aspnetCount aspnet), anchor, TOC, search and fallback checks across $($pages.Count) served API pages."
     }
 } finally {
     $client.Dispose()
diff --git a/tests/framework-view/fixture/ModernApi/Endpoint.cs b/tests/framework-view/fixture/ModernApi/Endpoint.cs
new file mode 100644
index 0000000..4e87989
--- /dev/null
+++ b/tests/framework-view/fixture/ModernApi/Endpoint.cs
@@ -0,0 +1,14 @@
+namespace FrameworkFixture.ModernApi;
+
+/// 
+/// An endpoint available only in modern .NET frameworks.
+/// 
+/// 
+/// 
+/// Return to Widget.
+/// 
+public class Endpoint
+{
+    /// Invokes the endpoint.
+    public void Invoke() { }
+}
diff --git a/tests/framework-view/fixture/ModernApi/ModernApi.csproj b/tests/framework-view/fixture/ModernApi/ModernApi.csproj
new file mode 100644
index 0000000..6e28b75
--- /dev/null
+++ b/tests/framework-view/fixture/ModernApi/ModernApi.csproj
@@ -0,0 +1,5 @@
+
+  
+    net11.0;net10.0
+  
+
diff --git a/tests/framework-view/fixture/Runtime/Widget.cs b/tests/framework-view/fixture/Runtime/Widget.cs
index 50a5b92..92d2ea2 100644
--- a/tests/framework-view/fixture/Runtime/Widget.cs
+++ b/tests/framework-view/fixture/Runtime/Widget.cs
@@ -3,6 +3,15 @@ namespace FrameworkFixture.Runtime;
 /// 
 /// A shared widget. See .
 /// 
+/// 
+/// Related APIs:
+/// modern feature link,
+/// standard feature link,
+/// legacy feature link,
+/// Modern Endpoint link,
+/// Standard Adapter link,
+/// missing page link.
+/// 
 public class Widget
 {
     /// Resets the widget.
@@ -22,6 +31,11 @@ public class Companion { }
 public class ModernFeature { }
 #endif
 
+#if NETSTANDARD2_1 || NETSTANDARD2_0
+/// An API documented only in .NET Standard views.
+public class StandardFeature { }
+#endif
+
 #if NET48
 /// An API documented in the .NET Framework view.
 public class LegacyFeature { }
diff --git a/tests/framework-view/fixture/StandardApi/Adapter.cs b/tests/framework-view/fixture/StandardApi/Adapter.cs
new file mode 100644
index 0000000..01e88b0
--- /dev/null
+++ b/tests/framework-view/fixture/StandardApi/Adapter.cs
@@ -0,0 +1,14 @@
+namespace FrameworkFixture.StandardApi;
+
+/// 
+/// An adapter available only in .NET Standard frameworks.
+/// 
+/// 
+/// 
+/// See Modern Endpoint.
+/// 
+public class Adapter
+{
+    /// Adapts a payload.
+    public void Adapt() { }
+}
diff --git a/tests/framework-view/fixture/StandardApi/StandardApi.csproj b/tests/framework-view/fixture/StandardApi/StandardApi.csproj
new file mode 100644
index 0000000..3302d17
--- /dev/null
+++ b/tests/framework-view/fixture/StandardApi/StandardApi.csproj
@@ -0,0 +1,5 @@
+
+  
+    netstandard2.1;netstandard2.0
+  
+
diff --git a/tests/framework-view/fixture/docfx.json b/tests/framework-view/fixture/docfx.json
index dbb1cff..f48143b 100644
--- a/tests/framework-view/fixture/docfx.json
+++ b/tests/framework-view/fixture/docfx.json
@@ -9,6 +9,16 @@
       "src": [{ "src": "..", "files": ["Utilities/Utilities.csproj"] }],
       "dest": "api/utilities",
       "memberLayout": "separatePages"
+    },
+    {
+      "src": [{ "src": "..", "files": ["ModernApi/ModernApi.csproj"] }],
+      "dest": "api/modern",
+      "memberLayout": "separatePages"
+    },
+    {
+      "src": [{ "src": "..", "files": ["StandardApi/StandardApi.csproj"] }],
+      "dest": "api/standard",
+      "memberLayout": "separatePages"
     }
   ],
   "build": {
diff --git a/tests/framework-view/fixture/index.md b/tests/framework-view/fixture/index.md
index 80885ba..2ba784e 100644
--- a/tests/framework-view/fixture/index.md
+++ b/tests/framework-view/fixture/index.md
@@ -2,4 +2,9 @@
 
 This page explains the compass.
 
-[Widget](xref:FrameworkFixture.Runtime.Widget)
+- [Widget](xref:FrameworkFixture.Runtime.Widget)
+- [Modern Endpoint](api/modern/FrameworkFixture.ModernApi.Endpoint.html)
+- [Modern Endpoint (unavailable view)](api/modern/FrameworkFixture.ModernApi.Endpoint.html?view=netstandard-2.0)
+- [Standard Adapter](api/standard/FrameworkFixture.StandardApi.Adapter.html)
+- [Standard Adapter (valid view)](api/standard/FrameworkFixture.StandardApi.Adapter.html?view=netstandard-2.0)
+- [Missing API](api/runtime/FrameworkFixture.Runtime.MissingPage.html)
diff --git a/tests/framework-view/fixture/toc.yml b/tests/framework-view/fixture/toc.yml
index 1446a60..5cf4a3b 100644
--- a/tests/framework-view/fixture/toc.yml
+++ b/tests/framework-view/fixture/toc.yml
@@ -4,3 +4,7 @@
   href: api/runtime/FrameworkFixture.Runtime.yml
 - name: Utilities API
   href: api/utilities/FrameworkFixture.Utilities.yml
+- name: Modern API
+  href: api/modern/FrameworkFixture.ModernApi.yml
+- name: Standard API
+  href: api/standard/FrameworkFixture.StandardApi.yml
diff --git a/tests/framework-view/framework-view.spec.js b/tests/framework-view/framework-view.spec.js
index e147fab..9240031 100644
--- a/tests/framework-view/framework-view.spec.js
+++ b/tests/framework-view/framework-view.spec.js
@@ -5,9 +5,15 @@ const widget = runtime + 'Widget.html';
 const reset = runtime + 'Widget.Reset.html';
 const companion = runtime + 'Companion.html';
 const modern = runtime + 'ModernFeature.html';
+const standard = runtime + 'StandardFeature.html';
 const legacy = runtime + 'LegacyFeature.html';
+const missingPage = runtime + 'MissingPage.html';
 const utilities = '/api/utilities/FrameworkFixture.Utilities.html';
 const utility = '/api/utilities/FrameworkFixture.Utilities.Utility.html';
+const modernNamespace = '/api/modern/FrameworkFixture.ModernApi.html';
+const modernEndpoint = '/api/modern/FrameworkFixture.ModernApi.Endpoint.html';
+const standardNamespace = '/api/standard/FrameworkFixture.StandardApi.html';
+const standardAdapter = '/api/standard/FrameworkFixture.StandardApi.Adapter.html';
 const net11 = 'net-11.0';
 const net10 = 'net-10.0';
 const standard21 = 'netstandard-2.1';
@@ -35,10 +41,13 @@ test.afterEach(async ({ page }) => {
     expect(pageErrors.get(page)).toEqual([]);
 });
 
-test('manifest determines the framework labels and default selection', async ({ page, request }) => {
+test('manifest determines the framework labels, availability and default selection', async ({ page, request }) => {
     const manifest = await (await request.get('/framework-views.json')).json();
     expect(manifest.apiPath).toBe('/api/');
     expect(manifest.viewOrder).toEqual([net11, net10, standard21, standard20, net48]);
+    expect(manifest.availability.sets[manifest.availability.pages['modern/FrameworkFixture.ModernApi.Endpoint.html']]).toEqual([net11, net10]);
+    expect(manifest.availability.sets[manifest.availability.pages['standard/FrameworkFixture.StandardApi.Adapter.html']]).toEqual([standard21, standard20]);
+    expect(manifest.availability.sets[manifest.availability.pages['runtime/FrameworkFixture.Runtime.LegacyFeature.html']]).toEqual([net48]);
 
     const defaultIndex = page.waitForResponse(response => new URL(response.url()).pathname === '/index.json');
     await page.goto(widget);
@@ -49,6 +58,7 @@ test('manifest determines the framework labels and default selection', async ({
         '.NET 11', '.NET 10', '.NET Standard 2.1', '.NET Standard 2.0', '.NET Framework 4.8'
     ]);
     await expect(page.locator(`article a[href$="${companion.split('/').pop()}"]`).first()).toBeVisible();
+    await expect(page.locator(`#navbar a[href="${viewed(standardNamespace, standard21)}"]`).first()).toBeVisible();
     await expect(page).toHaveURL(widget);
 
     await page.goto('/index.html');
@@ -77,39 +87,45 @@ for (const fragment of ['#missing%', '#%FF', '#unknown-anchor']) {
     });
 }
 
-test('an encoded member fragment resolves through the native xref maps', async ({ page }) => {
-    await page.goto(viewed(reset, net11));
+test('an encoded member fragment resolves through the native xref maps using unified precedence', async ({ page }) => {
+    await page.goto(viewed(reset, net10));
     const declaration = page.locator('article [data-uid="FrameworkFixture.Runtime.Widget.Reset(System.Int32)"]');
     const id = await declaration.getAttribute('id');
     const encodedId = '%46' + id.slice(1);
     expect(decodeURIComponent(encodedId)).toBe(id);
-    await page.goto(viewed(reset, net11) + '#' + encodedId);
+    await page.goto(viewed(reset, net10) + '#' + encodedId);
     await selector(page).selectOption(standard20);
-    await expect(page).toHaveURL(viewed(reset, standard21) + '#' + id);
+    await expect(page).toHaveURL(viewed(reset, net11) + '#' + id);
     await expect(declaration).toBeVisible();
-    await expect(selector(page)).toHaveValue(standard21);
-    await expect(status(page)).toContainText('Showing .NET Standard 2.1.');
+    await expect(selector(page)).toHaveValue(net11);
+    await expect(status(page)).toContainText('Showing .NET 11.');
 });
 
-test('fallback navigates once to the nearest newer view and then keeps it', async ({ page, request }) => {
-    await page.goto(viewed(modern, net11));
-    await expect(selector(page)).toHaveValue(net11);
+test('selector fallback targets the first framework in precedence order for both default and non-default APIs', async ({ page }) => {
+    // Fallback targeting the default framework (.NET 11)
+    await page.goto(viewed(modern, net10));
+    await expect(selector(page)).toHaveValue(net10);
     const navigations = [];
     page.on('request', request => {
         if (request.isNavigationRequest()) navigations.push(request);
     });
     await selector(page).selectOption(standard21);
-    await expect(page).toHaveURL(viewed(modern, net10));
-    await expect(selector(page)).toHaveValue(net10);
-    await expect(status(page)).toHaveText('This API is not documented for .NET Standard 2.1. Showing .NET 10.');
+    await expect(page).toHaveURL(viewed(modern, net11));
+    await expect(selector(page)).toHaveValue(net11);
+    await expect(status(page)).toHaveText('This API is not documented for .NET Standard 2.1. Showing .NET 11.');
     await selector(page).selectOption(standard21);
-    await expect(status(page)).toHaveText('This API is not documented for .NET Standard 2.1. Showing .NET 10.');
-    await expect(selector(page)).toHaveValue(net10);
-    expect(navigations.map(request => new URL(request.url()).search)).toEqual(['?view=' + net10]);
+    await expect(status(page)).toHaveText('This API is not documented for .NET Standard 2.1. Showing .NET 11.');
+    await expect(selector(page)).toHaveValue(net11);
+    expect(navigations.map(request => new URL(request.url()).search)).toEqual(['?view=' + net11]);
     expect(navigations[0].redirectedFrom()).toBeNull();
-    const missing = await request.get(viewed(modern, standard21), { maxRedirects: 0 });
-    expect(missing.status()).toBe(404);
-    expect(missing.headers().location).toBeUndefined();
+
+    // Fallback targeting a non-default framework (.NET Standard 2.1)
+    await page.goto(viewed(standard, standard20));
+    await expect(selector(page)).toHaveValue(standard20);
+    await selector(page).selectOption(net11);
+    await expect(page).toHaveURL(viewed(standard, standard21));
+    await expect(selector(page)).toHaveValue(standard21);
+    await expect(status(page)).toHaveText('This API is not documented for .NET 11. Showing .NET Standard 2.1.');
 });
 
 test('an API documented only in an older view stays there', async ({ page }) => {
@@ -120,6 +136,194 @@ test('an API documented only in an older view stays there', async ({ page }) =>
     await expect(selector(page)).toHaveValue(net48);
 });
 
+test('global navigation resolves unavailable API sections to default and non-default fallbacks and preserves available views', async ({ page }) => {
+    // Reproduces the Cuemon scenario: on netstandard-2.0, click an API section only available in modern .NET -> falls back to net-11.0
+    await page.goto(viewed(widget, standard20));
+    await expect(selector(page)).toHaveValue(standard20);
+    const modernNavLink = page.locator(`#navbar a[href="${viewed(modernNamespace, net11)}"]`).first();
+    await expect(modernNavLink).toBeVisible();
+    const modernToc = page.waitForResponse(response => {
+        const url = new URL(response.url());
+        return url.pathname === '/api/modern/toc.json' && url.searchParams.get('view') === net11;
+    });
+    const modernIndex = page.waitForResponse(response => new URL(response.url()).pathname === '/_framework-search/net11/index.json');
+    await modernNavLink.click();
+    await expect(page).toHaveURL(viewed(modernNamespace, net11));
+    expect((await modernToc).ok()).toBeTruthy();
+    expect((await modernIndex).ok()).toBeTruthy();
+    await expect(selector(page)).toHaveValue(net11);
+    await expect(page.locator('article h1')).toContainText('FrameworkFixture.ModernApi');
+    await expect(page.locator(`#toc a[href="${viewed(modernEndpoint, net11)}"]`).first()).toBeVisible();
+
+    // Browser history Back/Forward works cleanly without redirect traps
+    await page.goBack();
+    await expect(page).toHaveURL(viewed(widget, standard20));
+    await expect(selector(page)).toHaveValue(standard20);
+    await page.goForward();
+    await expect(page).toHaveURL(viewed(modernNamespace, net11));
+    await expect(selector(page)).toHaveValue(net11);
+
+    // On net-10.0, clicking Modern API preserves net-10.0
+    await page.goto(viewed(widget, net10));
+    await page.locator(`#navbar a[href="${viewed(modernNamespace, net10)}"]`).first().click();
+    await expect(page).toHaveURL(viewed(modernNamespace, net10));
+    await expect(selector(page)).toHaveValue(net10);
+
+    // On net-11.0, clicking Standard API (unavailable in net-11.0 and net-10.0) falls back to non-default netstandard-2.1
+    await page.goto(viewed(widget, net11));
+    const standardNavLink = page.locator(`#navbar a[href="${viewed(standardNamespace, standard21)}"]`).first();
+    await expect(standardNavLink).toBeVisible();
+    const standardToc = page.waitForResponse(response => {
+        const url = new URL(response.url());
+        return url.pathname === '/api/standard/toc.json' && url.searchParams.get('view') === standard21;
+    });
+    const standardIndex = page.waitForResponse(response => new URL(response.url()).pathname === '/_framework-search/netstandard2.1/index.json');
+    await standardNavLink.click();
+    await expect(page).toHaveURL(viewed(standardNamespace, standard21));
+    expect((await standardToc).ok()).toBeTruthy();
+    expect((await standardIndex).ok()).toBeTruthy();
+    await expect(selector(page)).toHaveValue(standard21);
+    await expect(page.locator('article h1')).toContainText('FrameworkFixture.StandardApi');
+    await expect(page.locator(`#toc a[href="${viewed(standardAdapter, standard21)}"]`).first()).toBeVisible();
+
+    // On netstandard-2.0, clicking Standard API preserves netstandard-2.0
+    await page.goto(viewed(widget, standard20));
+    await page.locator(`#navbar a[href="${viewed(standardNamespace, standard20)}"]`).first().click();
+    await expect(page).toHaveURL(viewed(standardNamespace, standard20));
+    await expect(selector(page)).toHaveValue(standard20);
+});
+
+test('ordinary internal API hyperlinks resolve availability, preserve query/fragment and support new tabs without click interception', async ({ page, context }) => {
+    await page.goto(viewed(widget, standard20));
+    await expect(page.locator(`article a[href="${viewed(modern, net11)}"]`)).toBeVisible();
+    await expect(page.locator(`article a[href="${viewed(standard, standard20)}"]`)).toBeVisible();
+    await expect(page.locator(`article a[href="${viewed(legacy, net48)}"]`)).toBeVisible();
+    await expect(page.locator(`article a[href="${modernEndpoint}?source=remarks&view=${net11}#details"]`)).toBeVisible();
+    await expect(page.locator(`article a[href="${standardAdapter}?source=remarks&view=${standard20}#details"]`)).toBeVisible();
+    // Genuine missing page keeps the requested view rather than fabricating a fallback.
+    await expect(page.locator(`article a[href="${viewed(missingPage, standard20)}"]`)).toBeVisible();
+
+    // Open a resolved fallback hyperlink in a new tab using a plain middle-click (no JS click handler interception).
+    const endpointLink = page.locator(`article a[href="${modernEndpoint}?source=remarks&view=${net11}#details"]`);
+    const [tab] = await Promise.all([
+        context.waitForEvent('page'),
+        endpointLink.click({ button: 'middle' })
+    ]);
+    await expect(tab).toHaveURL(`${modernEndpoint}?source=remarks&view=${net11}#details`);
+    await expect(selector(tab)).toHaveValue(net11);
+    await expect(tab.locator('article h1')).toContainText('Endpoint Class');
+    await tab.close();
+
+    // Conceptual pages also resolve API links targeting unavailable views or non-default-only APIs.
+    await page.goto('/index.html');
+    await expect(page.locator(`article a[href="${modernEndpoint.slice(1)}"]`).first()).toBeVisible();
+    await expect(page.locator(`article a[href="${viewed(modernEndpoint, net11)}"]`).first()).toBeVisible();
+    await expect(page.locator(`article a[href="${viewed(standardAdapter, standard21)}"]`).first()).toBeVisible();
+    await expect(page.locator(`article a[href="${viewed(standardAdapter.slice(1), standard20)}"]`).first()).toBeVisible();
+    await expect(page.locator(`article a[href$="${missingPage.split('/').pop()}"]`).first()).toBeVisible();
+});
+
+test('JavaScript-disabled navigation resolves fallback via HTTP 302 and preserves query parameters, fragments and history', async ({ browser }) => {
+    const context = await browser.newContext({ javaScriptEnabled: false });
+    const page = await context.newPage();
+    try {
+        await page.goto(viewed(widget, standard20));
+        await expect(page).toHaveURL(viewed(widget, standard20));
+
+        // Direct navigation to default fallback with unrelated query params and fragment
+        await page.goto(`${modernEndpoint}?tag=a&view=${standard20}&tag=b#details`);
+        await expect(page).toHaveURL(`${modernEndpoint}?tag=a&tag=b&view=${net11}#details`);
+        await expect(page.locator('article h1')).toContainText('Endpoint Class');
+
+        // Back/Forward across server-side 302 redirect has no redirect loop
+        await page.goBack();
+        await expect(page).toHaveURL(viewed(widget, standard20));
+        await page.goForward();
+        await expect(page).toHaveURL(`${modernEndpoint}?tag=a&tag=b&view=${net11}#details`);
+
+        // Clicking a static HTML link in Widget remarks to a non-default-only API while JS is disabled triggers HTTP 302
+        await page.goto(widget);
+        await page.locator('article a', { hasText: 'Standard Adapter link' }).click();
+        await expect(page).toHaveURL(`${standardAdapter}?source=remarks&view=${standard21}#details`);
+        await expect(page.locator('article h1')).toContainText('Adapter Class');
+    } finally {
+        await context.close();
+    }
+});
+
+test('direct HTTP routing redirects unavailable page/framework combinations with 302 and preserves 404, 400 and isolation', async ({ request }) => {
+    const redirectCases = [
+        // Unavailable section -> default fallback
+        { from: viewed(modernEndpoint, standard20), to: viewed(modernEndpoint, net11) },
+        { from: viewed(modernEndpoint, standard21), to: viewed(modernEndpoint, net11) },
+        { from: `${modernEndpoint}?tag=a&view=${standard20}&tag=b`, to: `${modernEndpoint}?tag=a&tag=b&view=${net11}` },
+        { from: `${modernEndpoint}?VIEW=${standard20}&tag=a`, to: `${modernEndpoint}?tag=a&view=${net11}` },
+        { from: `${modernEndpoint}?tag=a&VIEW=${standard20}&view=${standard21}&tag=b`, to: `${modernEndpoint}?tag=a&tag=b&view=${net11}` },
+        { from: viewed(modern, standard21), to: viewed(modern, net11) },
+        // Unavailable section / type -> non-default fallback
+        { from: standardAdapter, to: viewed(standardAdapter, standard21) },
+        { from: viewed(standardAdapter, net11), to: viewed(standardAdapter, standard21) },
+        { from: `${standardAdapter}?tag=x&tag=y`, to: `${standardAdapter}?tag=x&tag=y&view=${standard21}` },
+        { from: viewed(standardAdapter, net48), to: viewed(standardAdapter, standard21) },
+        { from: viewed(standard, net10), to: viewed(standard, standard21) },
+        { from: legacy, to: viewed(legacy, net48) },
+        { from: viewed(legacy, net11), to: viewed(legacy, net48) },
+        { from: `${legacy}?view=`, to: viewed(legacy, net48) }
+    ];
+
+    for (const item of redirectCases) {
+        const response = await request.get(item.from, { maxRedirects: 0 });
+        expect(response.status(), item.from).toBe(302);
+        expect(response.headers().location, item.from).toBe(item.to);
+        expect(response.headers()['cache-control'], item.from).toContain('no-store');
+        expect(response.headers().etag, item.from).toBeUndefined();
+
+        const followed = await request.get(item.to, { maxRedirects: 0 });
+        expect(followed.status(), item.to).toBe(200);
+        expect(followed.headers().location, item.to).toBeUndefined();
+    }
+
+    // Preserved available views return 200 directly
+    for (const okPath of [
+        viewed(modernEndpoint, net10),
+        viewed(standardAdapter, standard20),
+        viewed(legacy, net48),
+        '/xrefmap.yml?view=' + standard20,
+        '/index.html?view=unknown',
+        '/public/docfx.min.css?view=unknown'
+    ]) {
+        const ok = await request.get(okPath, { maxRedirects: 0 });
+        expect(ok.status(), okPath).toBe(200);
+    }
+
+    // Genuine missing pages, non-HTML API resources and internal framework directories return 404 without redirecting
+    for (const notFoundPath of [
+        missingPage,
+        viewed(missingPage, standard20),
+        '/api/modern/toc.json?view=' + standard20,
+        '/api/standard/toc.json',
+        '/api/modern/missing.png?view=' + standard20,
+        '/_frameworks/net10' + widget
+    ]) {
+        const notFound = await request.get(notFoundPath, { maxRedirects: 0 });
+        expect(notFound.status(), notFoundPath).toBe(404);
+        expect(notFound.headers().location, notFoundPath).toBeUndefined();
+    }
+
+    // Unknown or wrong-case framework identifiers return 400 without redirecting
+    for (const badViewPath of [
+        viewed(modernEndpoint, 'unknown'),
+        viewed(modernEndpoint, 'NET-11.0'),
+        viewed(missingPage, 'unknown'),
+        '/xrefmap.yml?view=unknown',
+        `${modernEndpoint}?view=${standard20}&view=${standard21}&view=${net48}`
+    ]) {
+        const bad = await request.get(badViewPath, { maxRedirects: 0 });
+        expect(bad.status(), badViewPath).toBe(400);
+        expect(bad.headers().location, badViewPath).toBeUndefined();
+    }
+});
+
 test('native TOC, breadcrumbs and cross-references stay in the view after reload and history', async ({ page }) => {
     const toc = page.waitForResponse(response => {
         const url = new URL(response.url());
@@ -172,7 +376,7 @@ test('explicit views load the index for the manifest directory', async ({ page,
 
 test('dynamic links preserve query and fragment without repeated DOM updates', async ({ page }) => {
     await page.goto(viewed(widget, net10));
-    const result = await page.evaluate(async ({ companion, net10, net11 }) => {
+    const result = await page.evaluate(async ({ companion, legacy, net10, net11, net48 }) => {
         const anchor = document.createElement('a');
         const initial = `${companion}?tag=a&tag=b&VIEW=${net11}&view=${net11}#details`;
         const expected = `${companion}?tag=a&tag=b&view=${net10}#details`;
@@ -183,18 +387,30 @@ test('dynamic links preserve query and fragment without repeated DOM updates', a
         document.querySelector('article').append(anchor);
         await new Promise(resolve => requestAnimationFrame(resolve));
         const rewritten = anchor.getAttribute('href');
+        anchor.setAttribute('href', `${legacy}?tag=a#details`);
+        await new Promise(resolve => requestAnimationFrame(resolve));
+        const fallback = anchor.getAttribute('href');
         anchor.setAttribute('href', '/index.html?tag=a#guide');
         await new Promise(resolve => requestAnimationFrame(resolve));
         const concept = anchor.getAttribute('href');
         anchor.setAttribute('href', 'https://example.com/api/page.html?tag=a#guide');
         await new Promise(resolve => requestAnimationFrame(resolve));
         observer.disconnect();
-        return { rewritten, expected, concept, external: anchor.getAttribute('href'), count: values.length };
-    }, { companion, net10, net11 });
+        return {
+            rewritten,
+            expected,
+            fallback,
+            expectedFallback: `${legacy}?tag=a&view=${net48}#details`,
+            concept,
+            external: anchor.getAttribute('href'),
+            count: values.length
+        };
+    }, { companion, legacy, net10, net11, net48 });
     expect(result.rewritten).toBe(result.expected);
+    expect(result.fallback).toBe(result.expectedFallback);
     expect(result.concept).toBe('/index.html?tag=a#guide');
     expect(result.external).toBe('https://example.com/api/page.html?tag=a#guide');
-    expect(result.count).toBe(3);
+    expect(result.count).toBe(5);
 });
 
 for (const [view, term, expected] of [[net10, 'ModernFeature', modern], [net48, 'LegacyFeature', legacy]]) {