diff --git a/CHANGELOG.md b/CHANGELOG.md index d5a0355..4a181e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,10 +4,19 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [1.1.1] - 2026-11-26 + +This is a patch release that adds destination-aware framework view fallback routing and branded HTTP error pages with client-side recovery, expands unit, container, Playwright, and Cuemon acceptance tests, and enforces the six-tag versioned Docker image policy without `:latest`. + +### Added + +- Added destination-aware framework view fallback (`framework-views/FrameworkViewConventions.ps1`, `framework-views/Build-DocfxFrameworkViews.ps1`, `framework-views/framework-views.nginx.conf`, and `templates/ms-style/public/framework-view.js`), generating an ordinal-keyed, deduplicated `availability` inventory (`sets` and `pages`) in `framework-views.json`, merging missing API section links into shared root `toc.json` by item name and normalized identity href, routing unavailable HTML pages and directory indexes via NGINX HTTP `302` fallback (stripping `view` parameters while preserving other query parameters and returning HTTP `400` for excess duplicate `view` parameters), and resolving destination-aware links in `framework-view.js` across navigation, search results, and the framework selector, +- Added branded HTTP error pages (`framework-views/DocfxHttpErrors.ps1`, `framework-views/http-error.md.tmpl`, `framework-views/http-error.js`, `framework-views/framework-views.nginx.conf`, `framework-views/Build-DocfxFrameworkViews.ps1`, and `framework-views/FrameworkViewConventions.ps1`), generating static DocFX error pages under `/_docfx-errors/` (reserving `_docfx-errors` in `Get-ApiPath`) for 19 HTTP status codes (`400`–`505`), routing HTML navigation errors to `/_docfx-errors/$status.html` and non-HTML requests to `@docfx_plain_error`, and serving isolated `public/docfx-http-error.js` recovery actions for documentation home, session-history back navigation, search, retry (including fresh `GET` navigation when URLs contain fragments), and `400`/`404` framework availability links, +- Added expanded automated verification (`tests/framework-view/http-error.spec.js`, `tests/framework-view/framework-view.spec.js`, `tests/framework-view/FrameworkViewConventions.Tests.ps1`, `tests/framework-view/Build-DocfxFrameworkViews.Tests.ps1`, `tests/Test-DocfxContainer.ps1`, `tests/framework-view/Test-FrameworkView.ps1`, `tests/framework-view/Test-FrameworkViews.ps1`, `tests/framework-view/cuemon/Build-CuemonFixture.ps1`, `tests/framework-view/cuemon/Test-CuemonFrameworkViews.ps1`, and `tests/framework-view/fixture/`) covering destination-aware fallback, identity-based TOC merging, ordinal page availability keys, and branded HTTP error pages for multi-TFM and single-TFM sites. ### Changed +- Updated repository documentation (`README.md`, `framework-views/README.md`, and `tests/framework-view/README.md`) to cover destination-aware framework view fallback, page availability metadata, shared root TOC merging, branded HTTP error pages, and the expanded browser and Cuemon acceptance tests, - Updated repository documentation (`README.md`, `framework-views/README.md`, `AGENTS.md`) and delivery tests (`tests/BuildAndPushDocfxImage.Tests.ps1`, `tests/ReleaseDelivery.Tests.ps1`) to document and enforce the six-tag versioned Docker image policy (three floating versioned convenience tags and three Codebelt engine-qualified tags). ### Removed @@ -104,7 +113,7 @@ This is the initial release of the DocFX builder Docker image. - Added a DocFX builder Docker image that includes the default and modern templates, - Added support for running the DocFX build process in a container. -[Unreleased]: https://github.com/codebeltnet/docfx/compare/v1.1.0..HEAD +[1.1.1]: https://github.com/codebeltnet/docfx/compare/v1.1.0..v1.1.1 [1.1.0]: https://github.com/codebeltnet/docfx/compare/v1.0.1..v1.1.0 [1.0.1]: https://github.com/codebeltnet/docfx/compare/v1.0.0..v1.0.1 [1.0.0]: https://github.com/codebeltnet/docfx/compare/v0.1.4..v1.0.0 diff --git a/README.md b/README.md index 610b1e2..a2f246b 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ This repository distributes the DocFX builder image, shared templates and native Framework views generate one native set of API pages, xrefs and search results per evaluated project target framework. From the consumer repository root, the generator reads `.docfx/docfx.json` and writes to `.bot/docfx`. The same PowerShell entry point runs on Windows, Linux, CI and in the builder image. Ordinary DocFX sites continue to use the standard CLI. [Framework views setup and migration](framework-views/README.md) +Sites served by the generated NGINX configuration automatically get branded HTTP error pages, including sites that target a single framework. [HTTP error pages](framework-views/README.md#http-error-pages) + Consuming repositories only need to provide their DocFX metadata and content with a command such as `ADD [".", "docfx"]` in their documentation Dockerfile. The image includes DocFX's `default` and `modern` templates and the Codebelt `ms-style` compatibility overlay. The overlay is intended for API reference sites maintained by the Codebelt ecosystem, including: diff --git a/framework-views/Build-DocfxFrameworkViews.ps1 b/framework-views/Build-DocfxFrameworkViews.ps1 index 70be7c0..693679d 100644 --- a/framework-views/Build-DocfxFrameworkViews.ps1 +++ b/framework-views/Build-DocfxFrameworkViews.ps1 @@ -13,6 +13,7 @@ $ErrorActionPreference = 'Stop' $PSNativeCommandUseErrorActionPreference = $false . "$PSScriptRoot/FrameworkViewConventions.ps1" . "$PSScriptRoot/DocfxMetadata.ps1" +. "$PSScriptRoot/DocfxHttpErrors.ps1" function Invoke-Step([string] $Log, [string] $Command, [string[]] $Arguments, [switch] $ReturnExitCode) { & $Command @Arguments *> $Log @@ -194,6 +195,7 @@ try { New-Item -ItemType Directory -Path $cacheRoot -Force | Out-Null } $restored = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) + $defaultView = @($views.Keys)[0] foreach ($view in $views.Keys) { $entry = $views[$view] $tfm = $entry.tfm @@ -263,6 +265,7 @@ try { }) New-Item -ItemType Directory -Path "$stage/framework-template" | Out-Null Copy-Item -LiteralPath $templateSource -Destination "$stage/framework-template/ms-style" -Recurse + if ($view -ceq $defaultView) { $errorStatuses = @(New-DocfxHttpErrors $stage $build $ApiPath) } Write-Json "$stage/framework-build.json" @{ build = $build } Invoke-Step "$stage/build.log" $docfx @('build', "$stage/framework-build.json") Write-Host "$view rendered $count metadata UIDs" @@ -271,7 +274,6 @@ try { Pop-Location } - $defaultView = @($views.Keys)[0] $site = "$work/site" Copy-Item -LiteralPath "$work/$($views[$defaultView].directory)/$buildDestination" -Destination $site -Recurse $routes = foreach ($view in $views.Keys) { @@ -301,9 +303,15 @@ 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 }) + Complete-DocfxHttpErrors $site $errorStatuses (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")). + Replace('__ERROR_STATUS__', ($errorStatuses -join ' ')) | Set-Content -LiteralPath "$work/nginx.conf" Write-Host "Site: $site" } finally { $outputLock.Dispose() diff --git a/framework-views/DocfxHttpErrors.ps1 b/framework-views/DocfxHttpErrors.ps1 new file mode 100644 index 0000000..85ee157 --- /dev/null +++ b/framework-views/DocfxHttpErrors.ps1 @@ -0,0 +1,55 @@ +function New-DocfxHttpErrors([string] $Stage, $Build, [string] $ApiPath) { + $source = "$Stage/framework-template/http-errors" + New-Item -ItemType Directory -Path $source | Out-Null + $template = Get-Content -LiteralPath "$PSScriptRoot/http-error.md.tmpl" -Raw + $errors = @( + ,@(400, 'Bad Request', 'Check the documentation address and any selected framework.') + ,@(401, 'Unauthorized', 'Sign in with an account that has access to this documentation.') + ,@(403, 'Forbidden', 'Your current access does not allow you to open this page.') + ,@(404, 'Not Found', 'The documentation page may have moved or the address may be incorrect.') + ,@(405, 'Method Not Allowed', 'Open the documentation page directly in your browser.') + ,@(408, 'Request Timeout', 'The request took too long to arrive. Try opening the page again.') + ,@(410, 'Gone', 'This documentation page has been removed. Search for its replacement.') + ,@(412, 'Precondition Failed', 'Open the page again to request its current version.') + ,@(413, 'Content Too Large', 'The request is too large. Try opening the page directly.') + ,@(414, 'URI Too Long', 'Shorten the address or search for the page from the documentation home.') + ,@(415, 'Unsupported Media Type', 'Open the documentation page directly in your browser.') + ,@(416, 'Range Not Satisfiable', 'Open the page again to request the complete document.') + ,@(429, 'Too Many Requests', 'Wait a moment before making another request.') + ,@(500, 'Internal Server Error', 'The page could not be served. Try again in a moment.') + ,@(501, 'Not Implemented', 'This request is unsupported. Open the page directly in your browser.') + ,@(502, 'Bad Gateway', 'The documentation is temporarily unavailable. Try again in a moment.') + ,@(503, 'Service Unavailable', 'The documentation is temporarily unavailable. Try again in a moment.') + ,@(504, 'Gateway Timeout', 'The request took too long to complete. Try again in a moment.') + ,@(505, 'HTTP Version Not Supported', 'Open the documentation in a current browser.') + ) + foreach ($errorPage in $errors) { + $code, $heading, $message = $errorPage + $page = $template.Replace('__STATUS__', $code).Replace('__HEADING__', $heading). + Replace('__MESSAGE__', $message).Replace('__API_PATH__', "/$ApiPath/") + Set-Content -LiteralPath "$source/$code.md" -Value $page + $code + } + $Build.content = @($Build['content'] ?? @()) + @{ src = 'framework-template/http-errors'; dest = '_docfx-errors'; files = @('*.md') } +} + +function Complete-DocfxHttpErrors([string] $Site, [int[]] $Statuses) { + # Compatible templates load this asset on documentation pages, where the recovery script records the last page. + Add-Content -LiteralPath "$Site/public/framework-view.js" -Value ("`n" + (Get-Content -LiteralPath "$PSScriptRoot/http-error.js" -Raw)) + Copy-Item -LiteralPath "$PSScriptRoot/http-error.js" -Destination "$Site/public/docfx-http-error.js" + $head = @' +$0 + + + + +'@ + foreach ($status in $Statuses) { + $path = "$Site/_docfx-errors/$status.html" + $html = Get-Content -LiteralPath $path -Raw + # Modern DocFX resolves these against location.href, independently of the HTML base URL. + $html = $html -creplace '(' -creplace ']*)?>', $head | + Set-Content -LiteralPath $path -NoNewline + } +} diff --git a/framework-views/FrameworkViewConventions.ps1 b/framework-views/FrameworkViewConventions.ps1 index 0737c11..dc49388 100644 --- a/framework-views/FrameworkViewConventions.ps1 +++ b/framework-views/FrameworkViewConventions.ps1 @@ -18,7 +18,7 @@ function Get-ApiPath($Metadata) { if (!$length) { throw 'Metadata destinations have no common API directory. Put all metadata.dest paths under one directory in docfx.json.' } $common = $common[0..($length - 1)] } - if ($common[0] -in 'public', '_frameworks', '_framework-search') { + if ($common[0] -in 'public', '_frameworks', '_framework-search', '_docfx-errors') { throw "Metadata destinations use the reserved directory '$($common[0])'. Choose a different API directory in docfx.json." } $common -join '/' @@ -83,3 +83,128 @@ 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 = [Collections.Specialized.OrderedDictionary]::new([StringComparer]::Ordinal) + $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 Get-NavigationTocIdentityHref([string] $Href) { + # DocFX can leave an API source link unresolved in one view and render it as HTML in another. + $Href -creplace '^/(?!/)', '' -creplace '^([^?#]+)\.yml(?=[?#]|$)', '$1.html' +} + +function Merge-NavigationTocItems($TargetItems, $CandidateItemLists, [string] $ApiPrefix, $Availability) { + $changed = $false + if (!$TargetItems) { return $false } + foreach ($item in $TargetItems) { + $relative = Resolve-FrameworkApiRelativePage $item['href'] $ApiPrefix + $needsDestination = $relative -and !$Availability.pages.Contains($relative) + if (!$needsDestination -and !$item['items']) { continue } + + $name = $item['name'] + if ([string]::IsNullOrWhiteSpace($name)) { continue } + $identityHref = Get-NavigationTocIdentityHref $item['href'] + $sameIdentity = { + [string]::Equals($_['name'], $name, [StringComparison]::Ordinal) -and + [string]::Equals((Get-NavigationTocIdentityHref $_['href']), $identityHref, [StringComparison]::Ordinal) + } + if (@($TargetItems | Where-Object $sameIdentity).Count -ne 1) { continue } + $candidates = @( + foreach ($candidateList in $CandidateItemLists) { + if (!$candidateList) { continue } + $matchingItems = @($candidateList | Where-Object $sameIdentity) + if ($matchingItems.Count -eq 1) { $matchingItems[0] } + } + ) + + if ($needsDestination) { + foreach ($candidate in $candidates) { + $candidateHref = $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['items']) { + $childCandidates = @( + foreach ($candidate in $candidates) { + if ($candidate['items']) { , $candidate['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..a63f8a7 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. @@ -79,6 +86,16 @@ docker build -f /path/to/docfx/framework-views/framework-views.Dockerfile -t my- docker run --rm -p 127.0.0.1:8080:8080 my-docs:local ``` +### HTTP error pages + +The generator renders branded error documents with the site's configured DocFX templates and packages them under the internal `/_docfx-errors/` directory. The generated NGINX configuration serves them automatically for document requests, even when the build has only one target framework. It keeps the original HTTP status and serves a short response for missing assets and other non-document requests. The error documents are excluded from the search index. + +The error page provides a documentation home link and expandable HTTP status details without JavaScript. With JavaScript, it shows the requested path, uses the site's saved theme, and offers the existing DocFX search when available. **Go back** checks the last successful documentation page recorded for the browser tab and falls back to the documentation home. The session record keeps the path and applicable framework view. **Retry** opens the original URL with a fresh GET for transient server errors. + +The usual automatic framework fallback takes precedence. If a request still fails and the framework inventory identifies that API page, the error page can show the selected framework and link to the available views in engine order. It checks that each destination responds directly before offering it and marks the default when available. Missing framework metadata leaves the standard recovery actions available. + +The feature applies to errors handled by the documentation site's generated NGINX configuration. When NGINX closes a timed-out connection before sending an HTTP response, the browser handles the connection failure. Sites built with the standard DocFX CLI and served through their own configuration use their host's error handling. Cloudflare, ingress controllers, load balancers and unavailable containers can respond before the request reaches the documentation server and control their own error pages. + ## OCI action integration Use an updated action and compatible builder image. Pin the action by full release commit SHA. Add these inputs alongside the existing version, revision and output inputs. [DocFX OCI build action](https://github.com/codebeltnet/docfx-oci-build) diff --git a/framework-views/framework-views.nginx.conf b/framework-views/framework-views.nginx.conf index 16e208a..eb84986 100644 --- a/framework-views/framework-views.nginx.conf +++ b/framework-views/framework-views.nginx.conf @@ -16,12 +16,55 @@ 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"; 304 "public, max-age=31536000, immutable"; } +map $uri $docfx_page_path { + default 0; + ~^/(?:public|_frameworks|_framework-search|_docfx-errors)(?:/|$) 0; + ~(?:/|\.html)$ 1; + ~/[^/.]+$ 1; +} + +map "$docfx_page_path:$http_sec_fetch_dest:$http_accept" $docfx_error_target { + default @docfx_plain_error; + ~^1:(?:document|iframe|frame): /_docfx-errors/$status.html; + ~*^1::(?:$|.*(?:text/html|\*/\*)) /_docfx-errors/$status.html; +} + server { listen 8080; server_name _; @@ -36,9 +79,28 @@ server { add_header Pragma "no-cache" always; add_header Vary "Accept-Encoding" always; + recursive_error_pages off; + error_page __ERROR_STATUS__ $docfx_error_target; + location ^~ /_docfx-errors/ { + internal; + try_files $uri @docfx_plain_error; + } + location @docfx_plain_error { + types {} + default_type text/plain; + # The error_page redirect retains the original status. + return 200 "The request could not be completed.\n"; + } + location ^~ __API__ { - if ($framework_root = invalid) { return 400 "Unknown documentation view."; } - try_files $framework_root$uri $framework_directory_index =404; + if ($framework_root = invalid) { return 400; } + 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; } +__FALLBACK__ + return 404; } location = /xrefmap.yml { if ($framework_root = invalid) { return 400 "Unknown documentation view."; } diff --git a/framework-views/http-error.js b/framework-views/http-error.js new file mode 100644 index 0000000..105f514 --- /dev/null +++ b/framework-views/http-error.js @@ -0,0 +1,169 @@ +(() => { + const historyKey = 'docfx:last-document'; + const current = new URL(location.href); + // The NGINX view argument is case-insensitive by name and uses the raw value. + const requestedView = current.search.match(/(?:^\?|&)view=([^&]*)/i)?.[1]; + const byId = id => document.getElementById(id); + + function rememberPage() { + const navigation = performance.getEntriesByType('navigation')[0]; + if (byId('docfx-http-error') || (navigation?.responseStatus >= 400)) return; + const api = document.querySelector('meta[name="docfx:framework-api"]')?.content; + const page = new URL(current.pathname, current.origin); + if (page.origin !== current.origin) return; + if (api && current.pathname.startsWith(api) && /^[a-z0-9.-]+$/.test(requestedView ?? '')) { + page.searchParams.set('view', requestedView); + } + try { + sessionStorage.setItem(historyKey, page.href); + } catch { + // Session storage may be unavailable in a restricted browser. + } + } + + async function isAvailable(url) { + try { + const response = await fetch(url, { method: 'HEAD', redirect: 'error', cache: 'no-store' }); + return response.ok && response.headers.get('content-type')?.startsWith('text/html'); + } catch { + return false; + } + } + + function setupBack() { + const back = byId('docfx-error-back'); + try { + const previous = new URL(sessionStorage.getItem(historyKey)); + if (previous.origin === current.origin && + (previous.pathname !== current.pathname || previous.searchParams.get('view') !== (requestedView || null))) { + back.href = previous.href; + } + } catch { + // The link already points home when there is no session history. + } + back.hidden = false; + back.addEventListener('click', async event => { + event.preventDefault(); + location.assign(await isAvailable(back.href) ? back.href : '/'); + }); + } + + function setupSearch() { + const search = byId('search-query'); + if (!search) return; + const action = byId('docfx-error-search'); + const enable = () => { + if (search.disabled) return; + action.hidden = false; + observer.disconnect(); + }; + const observer = new MutationObserver(enable); + observer.observe(search, { attributes: true, attributeFilter: ['disabled'] }); + enable(); + byId('search-results')?.addEventListener('click', event => { + // DocFX handles pagination in place. Its "#" links must stay on this URL. + if (event.target.closest('a[href="#"]')) event.preventDefault(); + }); + action.addEventListener('click', () => { + const panel = byId('navpanel'); + const toggle = document.querySelector('[aria-controls="navpanel"]'); + if (panel && toggle?.offsetWidth && !panel.classList.contains('show')) { + panel.addEventListener('shown.bs.collapse', () => search.focus(), { once: true }); + toggle.click(); + } else { + search.focus(); + } + }); + } + + async function showFrameworkContext({ status, apiPath }) { + if (!apiPath || !current.pathname.startsWith(apiPath)) return; + try { + const response = await fetch('/framework-views.json'); + if (!response.ok) return; + const manifest = await response.json(); + if (manifest.schemaVersion !== 1 || manifest.apiPath !== apiPath) return; + + const selected = requestedView || manifest.defaultView; + const label = manifest.views[selected]?.tfm; + if (typeof label === 'string') showDetail('view', label); + if (status !== '400' && status !== '404') return; + const relative = decodeURIComponent(current.pathname.slice(apiPath.length)); + const page = relative.endsWith('/') || !relative ? relative + 'index.html' : relative; + const setIndex = manifest.availability?.pages?.[page]; + if (typeof setIndex !== 'number') return; + const available = manifest.availability.sets[setIndex]; + if (!Array.isArray(available) || (status === '400' && available.includes(selected))) return; + if (!label && status === '404') return; + + // The build has already ordered and resolved this page's availability. Verify + // the direct links in case the deployed files and inventory have drifted. + const targets = await Promise.all(available.filter(view => view !== selected).map(async view => { + const entry = manifest.views[view]; + if (typeof entry?.tfm !== 'string') return null; + const target = new URL(current.pathname, current.origin); + if (target.origin !== current.origin) return null; + target.searchParams.set('view', view); + if (!await isAvailable(target)) return null; + const link = document.createElement('a'); + link.href = target.href; + link.textContent = entry.tfm + (view === manifest.defaultView ? ' (default)' : ''); + const item = document.createElement('li'); + item.append(link); + return item; + })); + const links = targets.filter(Boolean); + if (!links.length) return; + const message = byId('docfx-error-framework-message'); + message.textContent = label + ? `${page} is unavailable for ${label}. Choose another target framework.` + : `The selected framework is unrecognized. Open ${page} in one of the following target frameworks.`; + message.hidden = false; + const list = byId('docfx-error-framework-links'); + list.append(...links); + list.hidden = false; + } catch { + // Missing or invalid metadata leaves the standard recovery actions available. + } + } + + function showDetail(name, value) { + const detail = byId('docfx-error-' + name); + detail.textContent = value; + detail.hidden = false; + byId('docfx-error-' + name + '-label').hidden = false; + } + + function initialize() { + const error = byId('docfx-http-error'); + if (!error) { + rememberPage(); + addEventListener('pageshow', rememberPage); + return; + } + showDetail('path', current.pathname); + setupBack(); + setupSearch(); + if (['500', '502', '503', '504'].includes(error.dataset.status)) { + const retry = byId('docfx-error-retry'); + retry.hidden = false; + retry.addEventListener('click', () => { + // Temporarily change the history URL so a fragment target triggers a document navigation. + if (current.href.includes('#')) { + const historyUrl = new URL(current); + historyUrl.searchParams.append('_docfx_retry', ''); + history.replaceState(history.state, '', historyUrl); + } + // A new navigation uses GET even after a failed POST and replaces the temporary history URL. + location.replace(current.href); + }); + } + showFrameworkContext(error.dataset); + } + + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', initialize, { once: true }); + } else { + initialize(); + } +})(); diff --git a/framework-views/http-error.md.tmpl b/framework-views/http-error.md.tmpl new file mode 100644 index 0000000..6b23475 --- /dev/null +++ b/framework-views/http-error.md.tmpl @@ -0,0 +1,35 @@ +--- +title: "__STATUS__ __HEADING__" +_noindex: true +_disableToc: true +_disableAffix: true +_disableBreadcrumb: true +_disableContribution: true +_disableNextArticle: true +_frameworkApi: "" +_googleAnalyticsTagId: "" +--- + +
+

HTTP __STATUS__

+

__HEADING__

+

__MESSAGE__

+ + +
+ Documentation home + + + +
+
+ Technical details +
+
HTTP status
__STATUS__ __HEADING__
+ + + + +
+
+
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..7c830bd 100644 --- a/tests/Test-DocfxContainer.ps1 +++ b/tests/Test-DocfxContainer.ps1 @@ -101,6 +101,9 @@ $requiredFiles = @( '/opt/docfx/framework-views/Build-DocfxFrameworkViews.ps1', '/opt/docfx/framework-views/FrameworkViewConventions.ps1', '/opt/docfx/framework-views/DocfxMetadata.ps1', + '/opt/docfx/framework-views/DocfxHttpErrors.ps1', + '/opt/docfx/framework-views/http-error.md.tmpl', + '/opt/docfx/framework-views/http-error.js', '/opt/docfx/framework-views/Resolve-DocfxProjects.cs', '/opt/docfx/framework-views/KeepCrossTargetReferences.targets', '/opt/docfx/framework-views/framework-views.nginx.conf', @@ -142,7 +145,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 +168,28 @@ 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|ERROR_STATUS)__' -or + !(Test-Path -LiteralPath (Join-Path $destination 'site/_docfx-errors/404.html') -PathType Leaf)) { 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..9e2aa24 100644 --- a/tests/framework-view/Build-DocfxFrameworkViews.Tests.ps1 +++ b/tests/framework-view/Build-DocfxFrameworkViews.Tests.ps1 @@ -120,12 +120,23 @@ switch ($args[0]) { } 'build' { $stage = Split-Path -Parent $args[1] - $site = Join-Path $stage ((Get-Content -LiteralPath $args[1] -Raw | ConvertFrom-Json).build.dest) + $render = (Get-Content -LiteralPath $args[1] -Raw | ConvertFrom-Json).build + $site = Join-Path $stage $render.dest New-Item -ItemType Directory -Path "$site/api" | Out-Null New-Item -ItemType Directory -Path "$site/public" | Out-Null + $errors = $render.content | Where-Object dest -CEQ '_docfx-errors' + if ($errors) { + New-Item -ItemType Directory -Path "$site/$($errors.dest)" | Out-Null + foreach ($page in Get-ChildItem -LiteralPath "$stage/$($errors.src)" -Filter '*.md') { + @('', + (Get-Content -LiteralPath $page.FullName -Raw), '') | + Set-Content -LiteralPath "$site/$($errors.dest)/$($page.BaseName).html" + } + } 'Fixture.Library' | Set-Content -LiteralPath "$site/api/Library.html" 'references: []' | Set-Content -LiteralPath "$site/xrefmap.yml" '{}' | Set-Content -LiteralPath "$site/index.json" + Copy-Item -LiteralPath "$stage/framework-template/ms-style/public/framework-view.js" -Destination "$site/public/" $asset = if ($scenario -eq 'different shared assets') { Split-Path -Leaf $stage } else { 'shared' } $asset | Set-Content -LiteralPath "$site/public/shared.js" } @@ -143,7 +154,22 @@ 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|ERROR_STATUS)__' + $nginx | Should -Match 'location @framework_fallback' + $nginx | Should -Match 'error_page 400 401 403 404 405 .* 429 500 501 502 503 504 .*\$docfx_error_target;' + $errorPage = Get-Content -LiteralPath "$output/site/_docfx-errors/404.html" -Raw + $errorPage | Should -Match '' + $errorPage | Should -Match '' + $errorPage | Should -Match 'data-status="404"' + $errorPage | Should -Match '_noindex: true' + $errorPage | Should -Match '

Not Found

' + $errorPage | Should -Match 'data-api-path="/api/"' + $errorPage | Should -Not -Match '__(STATUS|HEADING|MESSAGE|API_PATH)__' + Test-Path -LiteralPath "$output/net10/_site/_docfx-errors" | Should -BeFalse @(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 @@ -174,6 +200,7 @@ switch ($args[0]) { & $build -DocfxConfig $config -OutputRoot $output -NoRestore Test-Path -LiteralPath "$output/net11/docs-output/api/Library.html" | Should -BeTrue Test-Path -LiteralPath "$output/net10" | Should -BeFalse + Test-Path -LiteralPath "$output/site/_docfx-errors/404.html" | Should -BeTrue Get-Content -LiteralPath "$fixture/dotnet.log" -Raw | Should -Not -Match '(?m)^restore ' } diff --git a/tests/framework-view/FrameworkViewConventions.Tests.ps1 b/tests/framework-view/FrameworkViewConventions.Tests.ps1 index 9eddc9b..1eecbb1 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' { @@ -18,6 +19,7 @@ Describe 'Framework view conventions' { { Get-ApiPath @(@{ dest = $pair[0] }, @{ dest = $pair[1] }) } | Should -Throw '*no common API directory*' } { Get-ApiPath @(@{ dest = '_frameworks/api' }) } | Should -Throw '*reserved directory*' + { Get-ApiPath @(@{ dest = '_docfx-errors/api' }) } | Should -Throw '*reserved directory*' } It 'orders framework families and numeric versions independently of discovery order' { @@ -92,3 +94,236 @@ 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 'preserves case-sensitive page availability entries across framework views' { + $site = (New-Item -ItemType Directory -Path "$TestDrive/avail-case-site").FullName + New-Item -ItemType Directory -Path "$site/api/ns", "$site/_frameworks/net10/api/ns" -Force | Out-Null + Set-Content -LiteralPath "$site/api/ns/Foo.html" 'net11' + Set-Content -LiteralPath "$site/_frameworks/net10/api/ns/foo.html" 'net10' + + $views = [ordered]@{ + 'net-11.0' = [ordered]@{ directory = 'net11' } + 'net-10.0' = [ordered]@{ directory = 'net10' } + } + + $availability = Get-FrameworkPageAvailability $site 'api' 'net-11.0' $views + @($availability.pages.Keys) | Should -BeExactly @('ns/Foo.html', 'ns/foo.html') + $availability.sets[$availability.pages['ns/Foo.html']] | Should -BeExactly @('net-11.0') + $availability.sets[$availability.pages['ns/foo.html']] | Should -BeExactly @('net-10.0') + $availability.pages.Contains('ns/FOO.html') | Should -BeFalse + } + + 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 'resolves reordered siblings to their own destinations' { + $availability = @{ pages = @{ 'First.html' = 0; 'Second.html' = 0 } } + $target = @( + @{ name = 'First API'; href = '/api/First.yml#members' } + @{ name = 'Second API'; href = 'api/Second.yml' } + ) + $candidates = , @( + @{ name = 'Second API'; href = 'api/Second.html' } + @{ name = 'First API'; href = 'api/First.html#members' } + ) + + Merge-NavigationTocItems $target $candidates 'api/' $availability | Should -BeTrue + $target[0].href | Should -BeExactly 'api/First.html#members' + $target[1].href | Should -BeExactly 'api/Second.html' + } + + It 'leaves a missing intermediate sibling unresolved and matches the following sibling' { + $availability = @{ pages = @{ 'First.html' = 0; 'Last.html' = 0 } } + $target = @( + @{ name = 'First API'; href = 'api/First.html' } + @{ name = 'Missing API'; href = 'api/Missing.yml' } + @{ name = 'Last API'; href = 'api/Last.yml' } + ) + $candidates = , @( + @{ name = 'First API'; href = 'api/First.html' } + @{ name = 'Last API'; href = 'api/Last.html' } + ) + + Merge-NavigationTocItems $target $candidates 'api/' $availability | Should -BeTrue + $target[1].href | Should -BeExactly 'api/Missing.yml' + $target[2].href | Should -BeExactly 'api/Last.html' + } + + It 'matches nested entries only within their matched parent and skips unrelated links with the same name' { + $availability = @{ pages = @{ 'Shared.html' = 0; 'Other.html' = 0; 'Match.html' = 0 } } + $target = @( + @{ name = 'Missing Group'; items = @(@{ name = 'Shared'; href = 'api/Shared.yml' }) } + @{ name = 'Group'; items = @( + @{ name = 'Shared'; href = 'api/Shared.yml' } + @{ name = 'Match'; href = 'api/Match.yml' } + ) } + ) + $candidates = , @( + @{ name = 'Other Group'; items = @(@{ name = 'Shared'; href = 'api/Shared.html' }) } + @{ name = 'Group'; items = @( + @{ name = 'Match'; href = 'api/Match.html' } + @{ name = 'Shared'; href = 'api/Other.html' } + ) } + ) + + Merge-NavigationTocItems $target $candidates 'api/' $availability | Should -BeTrue + $target[0].items[0].href | Should -BeExactly 'api/Shared.yml' + $target[1].items[0].href | Should -BeExactly 'api/Shared.yml' + $target[1].items[1].href | Should -BeExactly 'api/Match.html' + } + + It 'skips ambiguous sibling identities in either TOC' { + $availability = @{ pages = @{ 'DuplicateTarget.html' = 0; 'DuplicateCandidate.html' = 0 } } + $target = @( + @{ name = 'Duplicate target'; href = 'api/DuplicateTarget.yml' } + @{ name = 'Duplicate target'; href = 'api/DuplicateTarget.yml' } + @{ name = 'Duplicate candidate'; href = 'api/DuplicateCandidate.yml' } + ) + $candidates = , @( + @{ name = 'Duplicate target'; href = 'api/DuplicateTarget.html' } + @{ name = 'Duplicate candidate'; href = 'api/DuplicateCandidate.html'; tocHref = 'api/one/toc.html' } + @{ name = 'Duplicate candidate'; href = 'api/DuplicateCandidate.html'; tocHref = 'api/two/toc.html' } + ) + + Merge-NavigationTocItems $target $candidates 'api/' $availability | Should -BeFalse + $target.href | Should -BeExactly @('api/DuplicateTarget.yml', 'api/DuplicateTarget.yml', 'api/DuplicateCandidate.yml') + } + + It 'requires a name and keeps framework precedence among matching available destinations' { + $availability = @{ pages = @{ 'Section.html' = 0; 'Unnamed.html' = 0 } } + $target = @( + @{ name = 'Section'; href = 'api/Section.yml#members' } + @{ href = 'api/Unnamed.yml' } + ) + $candidates = @( + , $null + , @( + @{ name = 'Section'; href = 'api/Section.html#examples' } + @{ name = 'section'; href = 'api/Section.html#members' } + @{ href = 'api/Unnamed.html' } + ) + , @(@{ name = 'Section'; href = 'api/Section.yml#members' }) + , @(@{ name = 'Section'; href = '/api/Section.html#members' }) + , @(@{ name = 'Section'; href = 'api/Section.html#members' }) + ) + + Merge-NavigationTocItems $target $candidates 'api/' $availability | Should -BeTrue + $target[0].href | Should -BeExactly '/api/Section.html#members' + $target[1].href | Should -BeExactly 'api/Unnamed.yml' + } + + 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..afd9f33 100644 --- a/tests/framework-view/README.md +++ b/tests/framework-view/README.md @@ -6,7 +6,7 @@ Use PowerShell 7 on the host. The native and browser suites also require the .NE ## Unit tests and coverage -Run with Pester 5. Measure all three PowerShell implementation files so the report includes the generator entry point. The unit tests exercise preflight checks, framework conventions, output ownership, and metadata recovery and publication with the external commands mocked. The native and packaged suites below exercise real project discovery, MSBuild, DocFX, cache reuse, rendering and packaging. +Run with Pester 5. Measure the PowerShell files under `framework-views/` so the report includes the generator entry point. The unit tests exercise preflight checks, framework conventions, output ownership, error-page generation, and metadata recovery and publication with the external commands mocked. The native and packaged suites below exercise real project discovery, MSBuild, DocFX, cache reuse, rendering and packaging. ```powershell $configuration = New-PesterConfiguration @@ -29,13 +29,15 @@ 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. + +The error-page checks run against the generated NGINX configuration for both multi-TFM and single-TFM fixtures. They cover local error statuses and headers, deep URLs and refresh, theme and search behavior, framework recovery, navigation history, missing assets and metadata, and core recovery without JavaScript. ```powershell Push-Location tests/framework-view @@ -47,9 +49,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 +63,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..112b2aa 100644 --- a/tests/framework-view/Test-FrameworkView.ps1 +++ b/tests/framework-view/Test-FrameworkView.ps1 @@ -13,7 +13,9 @@ $repo = (Resolve-Path -LiteralPath "$PSScriptRoot/../..").Path $work = Join-Path ([IO.Path]::GetTempPath()) "docfx-browser-$([guid]::NewGuid().ToString('N'))" $output = "$work/output" $container = $null +$singleContainer = $null $previousOrigin = $env:DOCFX_TEST_ORIGIN +$previousSingleOrigin = $env:DOCFX_TEST_SINGLE_ORIGIN function Copy-Fixture([string] $Destination) { Copy-Item -LiteralPath "$PSScriptRoot/fixture" -Destination $Destination -Recurse @@ -46,7 +48,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 +67,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|ERROR_STATUS)__') { + 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] @@ -109,7 +122,7 @@ try { Copy-Fixture "$work/fixture" $docs = "$work/fixture/.docfx" & "$repo/framework-views/Build-DocfxFrameworkViews.ps1" -DocfxConfig "$docs/docfx.json" -OutputRoot $output - foreach ($path in 'site/framework-views.json', 'nginx.conf') { + foreach ($path in 'site/framework-views.json', 'site/_docfx-errors/404.html', 'nginx.conf') { $native = (Get-Content -LiteralPath "$output/$path" -Raw).Replace("`r`n", "`n") $packaged = (Get-Content -LiteralPath "$work/container-fixture/.bot/docfx/$path" -Raw).Replace("`r`n", "`n") if ($native -cne $packaged) { throw "Native and packaged generation differ for '$path'." } @@ -125,6 +138,20 @@ try { docker run --rm --mount "type=bind,source=$single,target=/stage" -w /stage $BuilderImage docfx build docfx.json Copy-Item -LiteralPath "$single/_site" -Destination "$output/site/single" -Recurse + # Run the same generated server against a site whose projects declare only one TFM. + $singleFixture = "$work/single-framework" + $singleOutput = "$work/single-output" + Copy-Fixture $singleFixture + $props = "$singleFixture/Directory.Build.props" + (Get-Content -LiteralPath $props -Raw).Replace( + 'net11.0;net10.0;netstandard2.1;netstandard2.0;net48', + 'net11.0') | Set-Content -LiteralPath $props + $singleConfig = "$singleFixture/.docfx/docfx.json" + $config = Get-Content -LiteralPath $singleConfig -Raw | ConvertFrom-Json -AsHashtable + $config.metadata = @($config.metadata[0]) + $config | ConvertTo-Json -Depth 20 | Set-Content -LiteralPath $singleConfig + & "$repo/framework-views/Build-DocfxFrameworkViews.ps1" -DocfxConfig $singleConfig -OutputRoot $singleOutput + $imageContext = "$work/image" New-Item -ItemType Directory -Path $imageContext | Out-Null Move-Item -LiteralPath "$output/site", "$output/nginx.conf" -Destination $imageContext @@ -134,7 +161,32 @@ try { $imageContext ) $siteImage = docker build @buildArguments - $container = docker run --rm -d -p 127.0.0.1::8080 $siteImage + $runtimeImage = if ($NginxImage) { $NginxImage } else { $siteImage } + $singleContainer = docker run --rm -d -p 127.0.0.1::8080 ` + --mount "type=bind,source=$singleOutput/site,target=/usr/share/nginx/html,readonly" ` + --mount "type=bind,source=$singleOutput/nginx.conf,target=/etc/nginx/conf.d/default.conf,readonly" $runtimeImage + $env:DOCFX_TEST_SINGLE_ORIGIN = "http://$((docker port $singleContainer 8080/tcp).Trim())" + + # Trigger otherwise uncommon local errors without adding production routes. + $testConfig = "$work/nginx-test.conf" + $routes = @' + add_header Allow $test_allow always; + add_header Retry-After $test_retry_after always; + location = /_status/401.html { + auth_basic "Fixture documentation"; + auth_basic_user_file /dev/null; + } +'@ + foreach ($status in 400, 403, 405, 410, 429, 500, 502, 503, 504) { + $routes += "`n location = /_status/$status.html { return $status; }" + } + @' +map $status $test_allow { default ""; 405 "GET, HEAD"; } +map $status $test_retry_after { default ""; 429 30; 503 60; } +'@ + "`n" + (Get-Content -LiteralPath "$imageContext/nginx.conf" -Raw).Replace('server {', "server {`n$routes`n") | + Set-Content -LiteralPath $testConfig + $container = docker run --rm -d -p 127.0.0.1::8080 ` + --mount "type=bind,source=$testConfig,target=/etc/nginx/conf.d/default.conf,readonly" $siteImage $endpoint = (docker port $container 8080/tcp).Trim() $env:DOCFX_TEST_ORIGIN = "http://$endpoint" Push-Location $PSScriptRoot @@ -145,6 +197,8 @@ try { } } finally { $env:DOCFX_TEST_ORIGIN = $previousOrigin + $env:DOCFX_TEST_SINGLE_ORIGIN = $previousSingleOrigin if ($container) { docker stop $container | Out-Null } + if ($singleContainer) { docker stop $singleContainer | Out-Null } Write-Host "Fixture artifacts: $work" } diff --git a/tests/framework-view/Test-FrameworkViews.ps1 b/tests/framework-view/Test-FrameworkViews.ps1 index d86fdcc..6e54b55 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' } @@ -214,19 +219,55 @@ if ($TestRouting) { @{ path = "/reference/runtime/?view=$otherView"; status = 200; body = 'other API index' } @{ 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/?view=unknown'; status = 400; body = '

Bad Request

' } + @{ 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 = '

Bad Request

' } + @{ 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; body = '

Not Found

' } + @{ 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..2c21820 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,47 @@ 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 + $notFound = Get-Page '/api/aspnet/DoesNotExist.html?view=netstandard-2.0' 404 'text/html' + Assert-True ($notFound.Contains('

Not Found

') -and $notFound.Contains('data-api-path="/api/"')) 'The document 404 did not render the Cuemon error page.' + Assert-True ($notFound.Contains('Cuemon for .NET') -and $notFound.Contains('images/50x50.png') -and $notFound.Contains('Copyright 2008-2026 Geekle')) 'The document 404 lost the configured Cuemon branding.' + Get-Page '/api/aspnet/toc.json?view=netstandard-2.0' 404 'text/plain' | 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 +220,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 +255,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 +276,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..d93e4b1 100644
--- a/tests/framework-view/fixture/docfx.json
+++ b/tests/framework-view/fixture/docfx.json
@@ -9,11 +9,22 @@
       "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": {
     "content": [{ "files": ["api/**/*.yml", "index.md", "toc.yml"] }],
     "globalMetadata": {
+      "_appName": "Framework Fixture",
       "_enableSearch": true,
       "_disableContribution": true
     },
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]]) {
diff --git a/tests/framework-view/http-error.spec.js b/tests/framework-view/http-error.spec.js
new file mode 100644
index 0000000..b5aa0da
--- /dev/null
+++ b/tests/framework-view/http-error.spec.js
@@ -0,0 +1,235 @@
+const { test, expect } = require('@playwright/test');
+
+const endpoint = '/api/modern/FrameworkFixture.ModernApi.Endpoint.html';
+const widget = '/api/runtime/FrameworkFixture.Runtime.Widget.html';
+const missing = '/deep/nested/documentation/does-not-exist.html';
+const back = page => page.getByRole('link', { name: 'Go back' });
+const heading = (page, name) => page.getByRole('heading', { name, exact: true });
+const alternatives = page => page.locator('#docfx-error-framework-links a');
+
+test('deep document errors reuse branding, assets, navigation and search', async ({ page, request }) => {
+    const assetErrors = [];
+    page.on('response', response => {
+        if (response.status() >= 400 && !response.request().isNavigationRequest()) {
+            assetErrors.push(new URL(response.url()).pathname);
+        }
+    });
+    expect((await page.goto(missing)).status()).toBe(404);
+    await expect(heading(page, 'Not Found')).toBeVisible();
+    await expect(page.locator('html')).toHaveAttribute('lang', 'en');
+    await expect(page.locator('.navbar-brand')).toContainText('Framework Fixture');
+    await expect(page.locator('#navbar a[href$="/index.html"]').first()).toBeVisible();
+    await expect(page.locator('footer')).toBeVisible();
+    await expect(page.locator('#docfx-http-error')).toHaveCSS('padding-top', '24px');
+    expect((await page.reload()).status()).toBe(404);
+    await expect(page).toHaveURL(missing);
+    await expect(alternatives(page)).toHaveCount(0);
+    await expect(back(page)).toHaveAttribute('href', '/');
+
+    await page.getByRole('button', { name: 'Search documentation' }).click();
+    const search = page.getByRole('searchbox', { name: 'Search', exact: true });
+    await expect(search).toBeFocused();
+    await search.fill('compass');
+    await expect(page.locator('#search-results .item-title a').first()).toHaveAttribute('href', '/index.html?q=compass');
+    expect(assetErrors).toEqual([]);
+
+    const index = await request.get('/index.json');
+    expect(await index.text()).not.toContain('_docfx-errors');
+});
+
+test('recovery remembers the last successful document across consecutive errors', async ({ page }) => {
+    const previous = widget + '?view=net-10.0';
+    expect((await page.goto(previous + '&tag=discarded')).status()).toBe(200);
+    expect((await page.goto(missing + '?token=secret-query-value')).status()).toBe(404);
+    await page.getByText('Technical details').click();
+    await expect(page.locator('#docfx-error-path')).toHaveText(missing);
+    await expect(page.locator('#docfx-http-error')).not.toContainText('secret-query-value');
+    const other = '/%3Cstrong%3Epath%3C%2Fstrong%3E.html';
+    expect((await page.goto(other)).status()).toBe(404);
+    await page.getByText('Technical details').click();
+    await expect(page.locator('#docfx-error-path')).toHaveText(other);
+    await expect(page.locator('#docfx-error-path strong')).toHaveCount(0);
+    await back(page).click();
+    await expect(page).toHaveURL(previous);
+    await expect(page.locator('#docfx-http-error')).toHaveCount(0);
+});
+
+test('automatic fallback takes precedence and an invalid request lists only working frameworks', async ({ page, request }) => {
+    const unavailable = endpoint + '?view=netstandard-2.0';
+    const fallback = await request.get(unavailable, { maxRedirects: 0 });
+    expect(fallback.status()).toBe(302);
+    expect(fallback.headers().location).toBe(endpoint + '?view=net-11.0');
+    expect((await page.goto(unavailable)).status()).toBe(200);
+    await expect(page).toHaveURL(endpoint + '?view=net-11.0');
+
+    const rejected = unavailable + '&view=netstandard-2.0&view=netstandard-2.0&token=secret-query-value';
+    expect((await page.goto(rejected)).status()).toBe(400);
+    await expect(heading(page, 'Bad Request')).toBeVisible();
+    await expect(page.locator('#docfx-error-framework-message')).toContainText('unavailable for netstandard2.0');
+    await expect(alternatives(page)).toHaveText(['net11.0 (default)', 'net10.0']);
+    await page.getByText('Technical details').click();
+    await expect(page.locator('#docfx-error-view')).toHaveText('netstandard2.0');
+    await expect(page.locator('#docfx-http-error')).not.toContainText('secret-query-value');
+    for (const link of await alternatives(page).all()) {
+        expect((await request.get(await link.getAttribute('href'), { maxRedirects: 0 })).status()).toBe(200);
+    }
+    await alternatives(page).last().click();
+    await expect(page).toHaveURL(endpoint + '?view=net-10.0');
+});
+
+test('missing framework metadata leaves standard actions available', async ({ page }) => {
+    const metadata = page.waitForResponse(response => new URL(response.url()).pathname === '/framework-views.json');
+    await page.route('**/framework-views.json', route => route.fulfill({ status: 404 }));
+    expect((await page.goto(endpoint + '?view=unavailable')).status()).toBe(400);
+    await metadata;
+    await expect(heading(page, 'Bad Request')).toBeVisible();
+    await expect(alternatives(page)).toHaveCount(0);
+    await back(page).click();
+    await expect(page).toHaveURL('/');
+});
+
+test('error recovery works with a compatible template that requires framework metadata', async ({ page }) => {
+    const scriptErrors = [];
+    page.on('pageerror', error => scriptErrors.push(error.message));
+    await page.route('**/public/framework-view.js', async route => {
+        const response = await route.fetch();
+        const script = await response.text();
+        await route.fulfill({
+            response,
+            body: `document.querySelector('meta[name="docfx:framework-api"]').content;\n${script}`
+        });
+    });
+
+    expect((await page.goto(missing)).status()).toBe(404);
+    await expect(back(page)).toBeVisible({ timeout: 3000 });
+    expect(scriptErrors).toEqual([]);
+});
+
+test('themes and search work on a narrow viewport', async ({ page }) => {
+    await page.setViewportSize({ width: 375, height: 740 });
+    await page.emulateMedia({ colorScheme: 'dark' });
+    await page.goto(missing);
+    await expect(page.locator('html')).toHaveAttribute('data-bs-theme', 'dark');
+    for (const theme of ['light', 'dark']) {
+        await page.evaluate(theme => localStorage.setItem('theme', theme), theme);
+        await page.reload();
+        await expect(page.locator('html')).toHaveAttribute('data-bs-theme', theme);
+        await expect(page.locator('body')).toHaveCSS('background-color',
+            theme === 'light' ? 'rgb(255, 255, 255)' : 'rgb(27, 27, 27)');
+    }
+    await page.getByRole('button', { name: 'Search documentation' }).click();
+    await expect(page.getByRole('searchbox', { name: 'Search', exact: true })).toBeFocused();
+    expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe(375);
+});
+
+test.describe('without JavaScript', () => {
+    test.use({ javaScriptEnabled: false });
+    test('retains branded styling, details and a working home link', async ({ page }) => {
+        expect((await page.goto(missing)).status()).toBe(404);
+        await expect(heading(page, 'Not Found')).toBeVisible();
+        await expect(page.locator('#docfx-http-error')).toHaveCSS('padding-top', '24px');
+        await page.getByText('Technical details').click();
+        await expect(page.getByText('404 Not Found', { exact: true })).toBeVisible();
+        await expect(back(page)).toBeHidden();
+        await page.getByRole('link', { name: 'Documentation home' }).click();
+        await expect(heading(page, 'Concept guide')).toBeVisible();
+    });
+});
+
+test('supported HTTP statuses and applicable headers are retained', async ({ request }) => {
+    const statuses = {
+        400: 'Bad Request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not Found',
+        405: 'Method Not Allowed', 410: 'Gone', 429: 'Too Many Requests',
+        500: 'Internal Server Error', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout'
+    };
+    for (const [code, title] of Object.entries(statuses)) {
+        const response = await request.get('/_status/' + code + '.html', { maxRedirects: 0 });
+        expect(response.status()).toBe(Number(code));
+        expect(response.headers()['content-type']).toContain('text/html');
+        expect(response.headers()['cache-control']).toContain('no-store');
+        expect(response.headers().location).toBeUndefined();
+        expect(await response.text()).toContain('

' + title + '

'); + if (code === '401') expect(response.headers()['www-authenticate']).toContain('Fixture documentation'); + if (code === '405') expect(response.headers().allow).toBe('GET, HEAD'); + if (code === '429') expect(response.headers()['retry-after']).toBe('30'); + if (code === '503') expect(response.headers()['retry-after']).toBe('60'); + } + expect((await request.post('/index.html')).status()).toBe(405); + const range = await request.get('/index.html', { headers: { range: 'bytes=99999999-' } }); + expect(range.status()).toBe(416); + expect(range.headers()['content-range']).toMatch(/^bytes \*\/\d+$/); + expect(await range.text()).toContain('

Range Not Satisfiable

'); + const head = await request.head(missing); + expect(head.status()).toBe(404); + expect(await head.text()).toBe(''); + + for (const [path, headers] of [ + ['/public/missing-01234567.js', {}], ['/_docfx-errors/404.html', {}], + [missing, { accept: 'application/json' }], [missing, { 'sec-fetch-dest': 'script' }] + ]) { + const response = await request.get(path, { headers }); + expect(response.status()).toBe(404); + expect(response.headers()['content-type']).toContain('text/plain'); + expect(response.headers()['cache-control']).toContain('no-store'); + expect(await response.text()).not.toContain('docfx-http-error'); + } +}); + +test('retry is explicit and opens the original URL', async ({ page }) => { + const url = '/_status/503.html?source=retry'; + expect((await page.goto(url)).status()).toBe(503); + const retry = page.getByRole('button', { name: 'Retry' }); + const navigation = page.waitForResponse(response => response.request().isNavigationRequest()); + await retry.click(); + expect((await navigation).status()).toBe(503); + await expect(page).toHaveURL(url); +}); + +for (const method of ['GET', 'POST']) { + test(`retry makes a fresh GET and keeps the fragment after a failed ${method}`, async ({ page }) => { + const path = '/_status/503.html?source=retry&tag=a%20b&tag=c'; + const url = path + '#members'; + const requests = []; + await page.route(target => target.pathname === '/_status/503.html', async route => { + const request = route.request(); + const target = new URL(request.url()); + requests.push([request.method(), target.pathname + target.search]); + if (requests.length === 1) { + await route.fulfill({ response: await route.fetch({ method: 'GET' }) }); + } else { + await route.fulfill({ contentType: 'text/html', body: '

Recovered

' }); + } + }); + + if (method === 'POST') { + await page.goto('/'); + await page.evaluate(url => { + const form = document.createElement('form'); + form.action = url; + form.method = 'POST'; + document.body.append(form); + form.submit(); + }, url); + } else { + await page.goto(url); + } + await expect(heading(page, 'Service Unavailable')).toBeVisible(); + await expect(page).toHaveURL(url); + await page.getByRole('button', { name: 'Retry' }).click(); + await expect(heading(page, 'Recovered')).toBeVisible({ timeout: 3000 }); + expect(requests).toEqual([[method, path], ['GET', path]]); + await expect(page).toHaveURL(url); + }); +} + +test('the generated server brands errors for sites with a single TFM', async ({ page, request }) => { + const origin = process.env.DOCFX_TEST_SINGLE_ORIGIN; + expect(origin).toBeTruthy(); + const manifest = await (await request.get(origin + '/framework-views.json')).json(); + expect(manifest.viewOrder).toEqual(['net-11.0']); + expect((await page.goto(origin + missing)).status()).toBe(404); + await expect(heading(page, 'Not Found')).toBeVisible(); + await expect(alternatives(page)).toHaveCount(0); + await page.getByRole('link', { name: 'Documentation home' }).click(); + await expect(heading(page, 'Concept guide')).toBeVisible(); +});