string InstanceName { get; init; }
Source
Gets the validated product identity included in safe alias diagnostics before the first lazy load.
Validates that an enabled protected Markdown download route names a policy the host actually registered.
Options validation catches missing or blank names. This startup check catches a misspelled name before AppSurface Docs maps an authorization-protected raw-source endpoint. The package deliberately resolves the host policy but never registers authentication schemes, identities, or a policy of its own.
Task StartAsync(CancellationToken cancellationToken)
Resolves the configured named policy when Markdown download is enabled.
Task StopAsync(CancellationToken cancellationToken)
Stops the validation service.
Loads, validates, and resolves the configured AppSurface Docs version catalog.
The service performs best-effort validation so a broken stored release tree becomes unavailable without preventing healthy versions or the live preview surface from loading. Validation is intentionally release-local: every version is checked independently for a readable tree root, the required landing and search pages, the search index, and the shared search runtime assets that exact-version pages depend on. Exact trees are otherwise treated as immutable, self-contained artifacts: outline-aware and rich-authoring exports should include the page-local runtimes they reference, while historical trees are not crawled or upgraded at host startup. Public AppSurfaceDocsResolvedVersion.AvailabilityIssue
values are sanitized for archive UI consumption, while filesystem paths and exception details stay in structured logs only.
AppSurfaceDocsResolvedVersionCatalog GetCatalog()
Returns the resolved version catalog for the current host.
The resolved catalog including availability information for each published version. Returns AppSurfaceDocsResolvedVersionCatalog.Disabled
when versioning is off for this host, AppSurfaceDocsResolvedVersionCatalog.EnabledWithoutCatalog
when versioning is on but no catalog path was configured, and enabled-but-unavailable semantics when a configured catalog or trusted release root could not be loaded into a usable published-release set.
string InstanceName { get; init; }
Source
Gets the validated product identity included in safe alias diagnostics before the first lazy load.
Represents the resolved version catalog used by the current host.
Status
CatalogPath
null
for the Disabled
and EnabledWithoutCatalog
sentinels, is typically an absolute filesystem path after successful resolution or file-based unavailability checks, and can remain the normalized configured value when Status
is AppSurfaceDocsResolvedVersionCatalogStatus.Unavailable
because absolute resolution failed before an unavailable catalog result was created. Versions
RecommendedVersion
null
when versioning is disabled, no recommendation was configured, the configured identifier did not resolve, or the matching release was hidden or unavailable after validation.
Disabled
means the host is running with versioning off, so callers should treat the live docs surface as the only public experience and skip published-release archive UI entirely.
EnabledWithoutCatalog
means versioning was turned on but no catalog path was configured, so callers can still expose the live preview surface but should not expect any published releases to resolve.
PublicVersions
preserves the ordering from Versions
after filtering by AppSurfaceDocsVersionVisibility.Public
only. Public-but-unavailable releases remain in that list so the archive can surface their degraded status instead of pretending they do not exist.
Aliases
contains operator-facing alias resolution state in authored order. Consumers that render the public archive must first create a safe projection; AppSurfaceDocsResolvedVersionAlias.ConfiguredVersion
may identify hidden configuration and must not be serialized into reader-facing markup.
IReadOnlyList<AppSurfaceDocsResolvedVersionAlias> Aliases { get; init; }
Source
Gets the resolved aliases in authored order. Invalid entries and every member of duplicate-name groups remain available here for operator diagnostics.
bool IsAliasNamespaceActive { get; init; }
Source
Gets whether alias declarations activate ownership of the configured alias namespace.
AppSurfaceDocsResolvedVersionCatalog Disabled { get; }
Source
Gets the sentinel catalog result for hosts where versioning is disabled entirely.
AppSurfaceDocsResolvedVersionCatalog EnabledWithoutCatalog { get; }
Source
Gets the sentinel catalog result for hosts where versioning is enabled but no catalog path was configured.
IReadOnlyList<AppSurfaceDocsResolvedVersion> PublicVersions { get; }
Source
Gets the public versions that should appear in the archive.
This list preserves the authored order from Versions
after filtering only by AppSurfaceDocsVersionVisibility.Public
. Versions stay in the list even when AppSurfaceDocsResolvedVersion.IsAvailable
is false
so archive consumers can show degraded-release messaging instead of silently dropping known public releases.
string? AvailabilityIssue { get; init; }
Source
Gets a sanitized catalog-level availability explanation when catalog or trusted-root configuration failed.
Version-level failures continue to live on AppSurfaceDocsResolvedVersion.AvailabilityIssue
. This property is for host-level failures such as a missing or unsafe trusted release root where no exact tree can be mounted safely.
Represents one resolved published docs version and its runtime availability.
Version
Label
Version
when no label is configured.Summary
null
when the catalog entry has no non-blank summary.ExactTreePath
null
when catalog path resolution failed before an exact tree could be selected.ExactRootUrl
SupportState
Visibility
AdvisoryState
IsAvailable
AvailabilityIssue
IsAvailable
is false
. Callers should branch on IsAvailable
first, then display this value when present; they should not infer availability by parsing message text. Internal logs retain filesystem paths and exception details, but this message is safe to surface in archive UI and reader-facing diagnostics. ReleaseManifestSha256
null
for unpinned legacy catalog entries and for entries whose configured digest is blank; a non-null value means the catalog requested release archive verification, not that verification necessarily succeeded. ArchiveVerificationState
AppSurfaceDocsReleaseArchiveVerificationState.AvailableUnverifiedLegacy
represents an available, shape-valid legacy tree without a catalog-pinned release manifest digest. Treat this state as meaningful only when IsAvailable
is true
; unavailable versions report AppSurfaceDocsReleaseArchiveVerificationState.Unavailable
and carry the public failure reason in AvailabilityIssue
. VerifiedReleaseArchive
null
unless IsAvailable
is true
and ArchiveVerificationState
is AppSurfaceDocsReleaseArchiveVerificationState.AvailableVerified
. When non-null, callers may rely on that invariant instead of rechecking catalog digest details. Resolves environment-aware visibility for AppSurface Docs harvest health routes and sidebar chrome.
bool AreRoutesExposed(AppSurfaceDocsOptions options, IHostEnvironment environment)
Resolves whether the harvest health controller routes should be registered or allowed for the current host.
This internal helper uses AppSurfaceDocsOptions.Harvest
health route settings and the supplied host environment. Missing health options fall back to AppSurfaceDocsHarvestHealthExposure.DevelopmentOnly
. Callers must pass the real host environment; the method null-checks both arguments before applying the environment-gated visibility contract.
bool ShouldShowChrome(AppSurfaceDocsOptions options, IHostEnvironment environment)
Resolves whether the sidebar should show harvest health chrome for the current host.
This internal helper uses AppSurfaceDocsOptions.Harvest
health chrome settings and the supplied host environment. Missing health options fall back to AppSurfaceDocsHarvestHealthExposure.DevelopmentOnly
. Callers use this for presentation chrome only; route exposure is resolved separately by AreRoutesExposed(AppSurfaceDocsOptions, IHostEnvironment)
. The method null-checks both arguments before applying the environment-gated visibility contract.
TextMateSharp-backed implementation of AppSurface Docs' internal code-block highlighting contract.
IGrammar? LoadGrammar(AppSurfaceDocsCodeLanguage language)
Loads the TextMate grammar for a normalized language, returning null
when no grammar exists.
language
The loaded grammar, or null
when the language has no TextMate scope.
void AppendTokens(StringBuilder builder, string line, IReadOnlyList<IToken> tokens)
Appends a tokenized source line while preserving unclassified gaps and trailing text.
builder
line
tokens
string? ResolveTokenClass(IReadOnlyList<string> scopes)
Maps TextMate scopes to AppSurface Docs' small semantic token vocabulary.
scopes
The AppSurface Docs token modifier, or null
for unstyled scopes.
Renders the single owned-failure view through the existing Docs shell before committing any bytes.
Task<string> RenderAsync(HttpContext context, string archiveRoot)
Buffers the normal Razor view so GET and HEAD share headers and no partial recovery can be sent.
context
archiveRoot
The shell-rendered generic recovery document.
Provides parser-input admission for source harvesters that need to bound bytes before decoding or parsing.
The helper reads at most maxFileSizeBytes + 1
bytes so oversized files can be rejected without loading the whole source into memory. Seekable streams still report their full file length in diagnostics when available.
Task<AppSurfaceDocsParserInputReadResult> ReadUtf8SourceAsync(string filePath, string relativePath, long maxFileSizeBytes, string configurationKey, string diagnosticCode, string harvesterType, string sourceKindLabel, string generatedSourceGuidance, CancellationToken cancellationToken)
Reads a source file through a positive byte budget and decodes it for parser consumption when it is within budget.
filePath
relativePath
maxFileSizeBytes
configurationKey
diagnosticCode
maxFileSizeBytes
.harvesterType
sourceKindLabel
generatedSourceGuidance
cancellationToken
A read result with AppSurfaceDocsParserInputReadResult.Included
set when the source is within budget and decoded, or skipped with a warning diagnostic when the budget is exceeded.
The method throws ArgumentOutOfRangeException
when maxFileSizeBytes
is zero or negative. Files are decoded with StreamReader
using UTF-8 as the default encoding and BOM detection enabled, so a recognized BOM is consumed instead of becoming source text. Oversized diagnostics use diagnosticCode
, configurationKey
, harvesterType
, sourceKindLabel
, and generatedSourceGuidance
to describe the skipped file and recovery path.
DocHarvestDiagnostic CreateFileTooLargeDiagnostic(string diagnosticCode, string harvesterType, string relativePath, long observedSizeBytes, long maxFileSizeBytes, string configurationKey, string sourceKindLabel, string generatedSourceGuidance)
Creates the warning diagnostic emitted when a parser-input budget rejects a source file.
diagnosticCode
harvesterType
relativePath
observedSizeBytes
maxFileSizeBytes
configurationKey
maxFileSizeBytes
.sourceKindLabel
generatedSourceGuidance
A non-strict warning diagnostic suitable for harvest health output.
Represents the outcome of a bounded parser-input read.
Included
true
when the source was within budget and Source
contains decoded text; false
when the source was skipped and Diagnostic
explains why. Source
null
.Diagnostic
null
.
Callers should branch on Included
before using Source
. Skipped results are intended to let harvesters continue processing sibling files while surfacing a visible diagnostic.
AppSurfaceDocsParserInputReadResult Read(string source)
Creates an included result for decoded source that stayed within the byte budget.
source
An included parser-input result with no diagnostic.
AppSurfaceDocsParserInputReadResult Skipped(DocHarvestDiagnostic diagnostic)
Creates a skipped result for a source file rejected before decoding or parsing.
diagnostic
A skipped parser-input result with no decoded source.
Logs a startup warning when non-development diagnostics reads are exposed without the shared read policy.
The warning is advisory and does not fail startup. This preserves compatibility for hosts that intentionally enforce diagnostics access through their application pipeline, reverse proxy, or network boundary, while making risky package exposure visible during deployment.
Task StartAsync(CancellationToken cancellationToken)
Logs the advisory startup warning when non-development diagnostics reads are exposed without a configured Diagnostics.OperatorReadPolicy
.
cancellationToken
A completed task after the advisory check has run.
Startup is never failed by this check. The method returns without logging in Development, when the shared read policy is configured, or when ResolveExposedDiagnosticsSurfaces
finds no exposed diagnostics surfaces. Otherwise, it logs the exposed surface names so operators can either configure the read policy or verify that host, reverse-proxy, or network authorization already protects those reads.
Task StopAsync(CancellationToken cancellationToken)
Stops the advisory startup warning service.
cancellationToken
A completed task.
The service does not hold background work or subscriptions after StartAsync
returns, so stopping is a no-op and always completes synchronously.
Builds the small static recovery-link set shared by browser docs recovery surfaces.
This builder only uses DocsUrlBuilder
and built-in public-section route contracts. It must not inspect harvested docs, search snapshots, or the missing request path. That constraint keeps standalone 404 pages deterministic during cold starts and prevents stale or hostile request paths from shaping recovery navigation. Callers that need search-result or representative-document fallback behavior should keep that logic in the search surface and adapt these links only as static route-safe entries.
IReadOnlyList<DocsRecoveryLink> BuildRecoveryLinks()
Builds the route-safe docs recovery links for the current live docs surface.
An ordered link set containing the primary search action, route-contract-backed Start Here and Packages section links, and the docs home link. The section and home links are marked export-ignorable because they are optional recovery affordances on sparse static exports; search remains crawlable so exported 404.html
pages keep a useful primary action when the search page is exported.
Verifies catalog-pinned AppSurface Docs release archive manifests.
The verifier treats the version catalog as trusted host configuration. It proves that the local exact-version tree matches the digest pinned by that catalog; it does not prove who built the archive or replace future signed attestation support.
bool TryVerify(string exactTreePath, string expectedManifestSha256, out AppSurfaceDocsVerifiedReleaseArchive? archive, out AppSurfaceDocsArchiveVerificationFailure? failure)
Attempts to verify an exact-version tree against the manifest digest pinned in the version catalog.
exactTreePath
expectedManifestSha256
archive
failure
true
when every required archive integrity check passes.
bool TryVerify(string exactTreePath, string expectedManifestSha256, AppSurfaceDocsReleaseArchiveFileSystem fileSystem, out AppSurfaceDocsVerifiedReleaseArchive? archive, out AppSurfaceDocsArchiveVerificationFailure? failure)
Attempts to verify an exact-version tree using the supplied filesystem adapter.
exactTreePath
expectedManifestSha256
fileSystem
archive
failure
true
when every required archive integrity check passes.
bool FileMatches(IFileInfo fileInfo, AppSurfaceDocsReleaseArchiveFile expectedFile)
Recomputes an already-verified file digest from an IFileInfo
before serving active content.
fileInfo
expectedFile
true
when length and SHA-256 still match the manifest entry.
Filesystem adapter used by release archive verification.
The production adapter reads the physical release tree. Tests use custom adapters to exercise portable failure branches such as unreadable files without depending on platform-specific chmod behavior.
StringComparer GetPathComparer(string rootPath)
Gets the comparer used by the physical filesystem when resolving paths beneath an archive root.
rootPath
The comparer matching the root's physical filesystem casing rules.
StringComparer ResolvePhysicalPathComparer(string rootPath, Func<string, bool> fileExists, Func<string, IEnumerable<string>> enumerateFileSystemEntries)
Resolves physical filesystem casing behavior without writing probe files into an immutable archive.
rootPath
fileExists
enumerateFileSystemEntries
An ordinal comparer matching the archive root's case behavior.
bool FileExists(string path)
Returns whether the path exists as a file.
byte[] ReadAllBytes(string path)
Reads all bytes from a file.
long GetLength(string path)
Returns the current file length in bytes.
string ComputeSha256(string path)
Computes a lowercase SHA-256 digest for a file.
IEnumerable<string> EnumerateFiles(string rootPath)
Enumerates files under an exact release tree.
AppSurfaceDocsReleaseArchiveFileSystem Physical { get; }
Source
Gets the physical filesystem adapter used by runtime verification.
Immutable file metadata from a verified release archive manifest.
Path
Length
ContentType
Sha256
Verified release archive metadata used by mounted published-tree handlers.
bool TryGetFile(string relativePath, out AppSurfaceDocsReleaseArchiveFile file)
Attempts to resolve verified metadata for a path the published-tree handler is about to serve.
relativePath
file
true
when the path is covered by the release manifest.
int FileCount { get; }
Source
Gets the number of files covered by the verified release manifest.
IEnumerable<string> CoveredPaths { get; }
Source
Gets the verified immutable inventory used for startup namespace collision checks.
AppSurfaceDocsFrozenRouteManifest FrozenRouteManifest { get; }
Source
Gets the route manifest parsed from verified release archive bytes.
Stable archive verification diagnostic surfaced through logs and sanitized availability messages.
Code
PublicMessage
Detail
Path
Normalizes browser-facing metadata hrefs that render as plain anchors.
AppSurfaceDocsMetadataHrefPolicyResult NormalizeTrustMigrationHref(string? href)
Normalizes trust.migration.href
and classifies it as absent, safe to render, or rejected.
href
An explicit policy result that distinguishes missing optional metadata from rejected unsafe metadata.
Result returned by metadata href normalization.
State
Href
null
when absent.AppSurfaceDocsMetadataHrefPolicyResult Absent()
Creates an absent href result for missing optional metadata.
An absent result with no href.
AppSurfaceDocsMetadataHrefPolicyResult Allowed(string href)
Creates an allowed href result.
href
An allowed result.
AppSurfaceDocsMetadataHrefPolicyResult Rejected(string href)
Creates a rejected href result.
href
A rejected result.
Checks immutable startup inventories before publishing the newly reserved alias subtree.
void Validate(AppSurfaceDocsResolvedVersionCatalog catalog, DocsUrlBuilder urls, ILogger? logger = null, string instanceName = "Default")
Rejects live/recommended ownership overlap without reserving anything for an inactive catalog.
catalog
urls
logger
instanceName
Resolves environment-aware visibility for AppSurface Docs maintainer diagnostics routes.
bool ShouldShowChrome(AppSurfaceDocsOptions options, IHostEnvironment environment)
Resolves whether the built-in sidebar should show route-inspector diagnostics chrome for the current host.
The default follows local-development ergonomics: Development hosts show route-inspector discovery by default, while non-development hosts must opt in explicitly. This method controls only docs chrome. It does not expose or authorize the route-inspector response; use IsRouteInspectorExposed
for route response policy.
bool IsRouteInspectorExposed(AppSurfaceDocsOptions options, IHostEnvironment environment)
Resolves whether the route-inspector controller routes should return responses for the current host.
The route inspector exposes route identity intended for local development and trusted operators. Missing diagnostics options fall back to AppSurfaceDocsHarvestHealthExposure.DevelopmentOnly
. Setting the exposure to AppSurfaceDocsHarvestHealthExposure.Always
only allows the controller response; hosts remain responsible for authentication, authorization, or network controls in production.
Represents one locale-prefixed public route candidate derived from a localized document variant.
SourcePath
Locale
TranslationKey
PublicRoutePath
Candidates are produced only for variants that have a public route and a configured locale route prefix. Source paths and public route paths are normalized relative docs paths, not absolute URLs.
Owns the route identity contract for one cached AppSurface Docs snapshot.
The catalog deliberately separates source identity from public route identity: source path -> internal lookup and authoring provenance public route path -> browser-facing canonical URL redirect alias -> declared or Markdown source-shaped URL that redirects to public route Controllers render only public canonical winners. Declared aliases and Markdown source-shaped paths for public winners redirect to the canonical route, while non-Markdown source paths, collision losers, and reserved routes stay non-public. Link builders can still resolve source paths so authored Markdown stays source-friendly without rendering source-shaped URLs into the reader-facing surface.
bool TryGetPublicRoutePathForSource(string sourcePath, out string publicRoutePath)
Resolves only an ordinal exact source identity, without canonical/alias lookup precedence. Snapshot metadata and recommendation facts use this after merge/deduplication so a source-shaped slug cannot impersonate another source. Legitimate fragment sources remain linkable under the existing fragment contract.
AppSurfaceDocsRouteManifest BuildRouteManifest()
Builds a snapshot-local manifest of public canonical routes and redirect aliases for export consumers.
A deterministic route manifest for the current catalog snapshot.
Use this when a downstream component needs a deterministic read model of canonical winners plus alias metadata. Prefer ResolvePublicRoute(string)
for live request-time route decisions. The returned entries are ordered from _publicIdentityByRoutePath
by public route path, then source path, using ordinal-ignore-case comparison so export output is stable across runs. Diagnostics start as a snapshot of Diagnostics
and are passed through BuildRouteManifestEntry
so implicit recovery-alias collisions discovered during manifest materialization are included in the returned AppSurfaceDocsRouteManifest
. Pitfall: this method does not mutate catalog state, and callers should not rely on reference equality with external diagnostic collections or assume manifest-only diagnostics were computed before this call.
IReadOnlyList<LocalizedDocRouteCandidate> BuildLocalizedRouteCandidates(LocalizedDocsGraph graph, AppSurfaceDocsLocalizationOptions options)
Builds locale-prefixed route candidates from a localized document graph.
graph
options
Sorted locale-prefixed candidates suitable for later route registration slices.
Returns an empty list when the graph is disabled. Variants are skipped when they have no public route, or when their locale no longer maps to a configured route prefix. The method is snapshot-local and does not mutate catalog state.
Resolves normalized AppSurface Docs theme options into render-ready CSS variables and shell attributes.
The resolved theme is safe to cache as a singleton because it contains only preset names, density/chrome flags, and sanitized CSS custom property declarations. Razor views emit these values into the exported HTML so live docs, static export, and published archives share the same frozen visual contract.
AppSurfaceDocsResolvedTheme Theme { get; }
Source
Gets the render-ready theme used by AppSurface Docs layouts.
Render-ready AppSurface Docs theme values.
Preset
Density
Chrome
PresetAttribute
data-docs-theme-preset
.DensityAttribute
data-docs-density
.ChromeAttribute
data-docs-chrome
.RootCssClass
CssVariables
CssVariableStyle
RootColorScheme
UsesSharedTheme
CriticalCss
UsesSharedTheme
is true
.Centralizes normalization, validation, and render-ready resolution for the AppSurface Docs theme contract.
Hosts configure AppSurfaceDocsThemeOptions
, while this policy keeps every consumer on one resolved theme boundary. Run Normalize
during post-configuration before calling Validate
or Resolve
.
void Normalize(AppSurfaceDocsThemeOptions theme)
Normalizes mutable theme options in place.
theme
This method creates omitted nested sections and canonicalizes configured CSS hex colors. Call it during post-configuration before validation or resolution so those later operations observe a stable options shape.
void Validate(AppSurfaceDocsThemeOptions? theme, List<string> failures)
Adds configuration failures for an AppSurface Docs theme.
theme
failures
Contrast checks use the selected preset's canvas and raised backgrounds because v1 intentionally does not expose raw surface overrides. This makes the reported contrast guarantee match the surfaces the package renders.
AppSurfaceDocsResolvedTheme Resolve(AppSurfaceDocsThemeOptions? options)
Resolves theme options into the attributes and CSS variables consumed by rendered and exported docs.
options
The immutable theme contract for layouts, search, and static output.
Call Normalize
before resolution for configured options. The null-tolerant fallback exists only to keep rendering defensive when no theme section is supplied.
void SetDerivedVariableForTesting(Dictionary<string, string> variables, string name, string value, bool requireExistingKeys)
Exercises the derived-token inventory guard through the supported internal test seam.
bool CanParseCssColorForTesting(string value, string canvasColor)
Exercises CSS-color parsing branches without exposing the parsed implementation type.
Allows a harvester to publish diagnostics and docs while opting out of aggregate strict-health counts.
Implement this for best-effort harvesters whose diagnostics should be visible to operators but whose empty, failed, timed-out, or canceled state must not decide whether DocHarvestHealthStatus.Failed
is returned.
bool ParticipatesInStrictHealth { get; }
Source
Gets a value indicating whether this harvester participates in aggregate strict-health success and failure totals.
Parses alias declarations while retaining the provenance needed for safe operator and archive projections.
AliasDeclaration Parse(JsonElement root)
Reads whether the alias namespace was declared and retains validatable alias metadata.
root
The declaration snapshot; it contains no retained JSON document state.
IReadOnlyList<AppSurfaceDocsResolvedVersionAlias> Resolve(AliasDeclaration declaration, IReadOnlyList<AppSurfaceDocsResolvedVersion> versions, bool targetResolutionAvailable = true)
Resolves parsed aliases by exact version identifier and creates immutable read models.
declaration
versions
targetResolutionAvailable
Resolved aliases in authored order, retaining conflicting entries for operator inspection.
Snapshot of declaration activity and parsed entries.
IsActive
Items
One parsed alias with independent name, metadata, and explicit-visibility provenance.
Index
Name
ConfiguredVersion
Label
Summary
null
when absent or blank.Visibility
HasExplicitPublicVisibility
IsDefinitionValid
DiagnosticCode
Resolved alias state for host routing and operator diagnostics. This is a non-positional record so future additive fields do not change constructor or deconstruction contracts.
ConfiguredVersion
is operator-side configuration and may identify a hidden release. Public archive consumers must use a deliberate safe projection instead of serializing this record. TargetVersion
is populated only for a known public target; it is the same resolved-version object used by exact-version mounts.
string? Name { get; init; }
Source
Gets the normalized validated name, or null
when the authored name is invalid.
string? Label { get; init; }
Source
Gets the validated reader-facing label, or null
when unavailable.
string? Summary { get; init; }
Source
Gets optional validated reader-facing summary text.
AppSurfaceDocsVersionVisibility? Visibility { get; init; }
Source
Gets the valid configured visibility, or null
when invalid.
string? ConfiguredVersion { get; init; }
Source
Gets the configured exact target identifier for operator inspection only.
AppSurfaceDocsResolvedVersion? TargetVersion { get; init; }
Source
Gets the existing resolved public exact-version target, or null
when not public or unresolved.
string? RootUrl { get; init; }
Source
Gets the alias root URL when the authored name is safe.
bool IsAvailable { get; init; }
Source
Gets whether the alias can be mounted on its verified public target.
bool IsDefinitionValid { get; init; }
Source
Gets whether the authored alias passed shape, name, and metadata validation.
bool HasExplicitPublicVisibility { get; init; }
Source
Gets whether a valid explicit Public visibility value was authored.
bool IsNameConflict { get; init; }
Source
Gets whether another entry has the same normalized name.
string? DiagnosticCode { get; init; }
Source
Gets the stable ASDOCSALIAS diagnostic code, or null
.
string? AvailabilityIssue { get; init; }
Source
Gets a sanitized availability explanation suitable for deliberate public projection.
Validates and normalizes repository-relative harvest path patterns and candidate paths.
The validator is stateless and thread-safe. Callers should normalize or validate before matching: backslashes are converted to /
, configured patterns are trimmed, and rooted, URI-like, drive-rooted, control-character, query, fragment, and parent-directory paths are rejected. NormalizeSlashes
only changes separators; it does not perform validation by itself.
bool IsValidConfiguredGlobPattern(string? pattern)
Returns whether a configured glob pattern is safe to evaluate as a repository-relative path policy rule.
pattern
true
when pattern
is repository-relative after trimming and slash normalization; otherwise false
.
Patterns starting with /
, ./
, or //
, containing ://
, drive roots, control characters, ?
, #
, or a ..
segment are invalid. Validation does not prove that a glob can match an existing file; it only rejects unsafe path forms before matcher construction.
bool TryNormalizeCandidatePath(string path, out string normalizedPath)
Attempts to normalize a candidate file or directory path before path-policy evaluation.
path
normalizedPath
true
when path
is a non-empty repository-relative path that is safe for policy evaluation; otherwise false
.
This method assumes callers have already chosen whether the path represents a file or directory. It trims no whitespace, so caller-provided spaces remain part of the candidate path; unsafe rooted, URI-like, drive-rooted, query, fragment, control-character, and parent-directory forms are rejected.
string NormalizeSlashes(string value)
Converts Windows path separators in value
to repository-style slash separators.
value
value
with each \
character replaced by /
.
This helper does not trim, validate, collapse duplicate separators, or reject unsafe segments. Use one of the validation methods when accepting configuration or candidate paths from outside the policy implementation.
Regex DriveRootedPatternRegex()
Generates the expression used to reject Windows drive-rooted patterns after slash normalization.
A culture-invariant regular expression that matches values such as C:/repo
.
Runs startup validation and harvest warmup for every finalized named AppSurface Docs runtime.
Named Docs products own isolated options and aggregators, so the legacy singleton preflight services cannot validate or warm them. This service runs after endpoint mapping, when the registry has constructed the immutable runtime snapshots, and preserves the same Markdown-policy validation, diagnostics warning, and harvest startup semantics that AddAppSurfaceDocs()
provides for a legacy single-instance host.
Task StartingAsync(CancellationToken cancellationToken)
Completes the pre-start lifecycle phase without touching named runtimes.
cancellationToken
A completed task because endpoint mapping has not necessarily run yet.
Hosts built through WebStartup
construct their endpoint table while the web host starts. Named Docs must wait for that work before resolving finalized runtimes, so strict preflight runs from StartedAsync
.
Task StartAsync(CancellationToken cancellationToken)
Completes the ordinary hosted-service start phase without touching named runtimes.
cancellationToken
A completed task because endpoint mapping may not yet have run.
Task StartedAsync(CancellationToken cancellationToken)
Validates and warms every named Docs runtime after all hosted services have started.
cancellationToken
A task that completes once all strict preflights complete or background warmups are scheduled.
IHostedLifecycleService.StartedAsync
runs after ordinary IHostedService.StartAsync
calls. That ordering lets conventional ASP.NET Core hosts map endpoints before this service reads the finalized named Docs registry, while preserving startup failure behavior for strict validation.
Task StoppingAsync(CancellationToken cancellationToken)
Completes the pre-stop lifecycle phase.
cancellationToken
A completed task because per-instance preflights own no shutdown work.
Task StopAsync(CancellationToken cancellationToken)
Stops the preflight service.
cancellationToken
A completed task because per-instance preflights own no shutdown work.
Task StoppedAsync(CancellationToken cancellationToken)
Completes the post-stop lifecycle phase.
cancellationToken
A completed task because per-instance preflights own no shutdown work.
Sanitizes rendered AppSurface Docs HTML using the package's docs-specific allowlist.
IAppSurfaceDocsHtmlSanitizer
exists to normalize rendered package documentation fragments before AppSurface Docs displays them. It is not a general-purpose user-generated-content sanitizer, JavaScript policy, or replacement for a host-owned Content Security Policy. Unsupported elements or attributes may be removed.
string Sanitize(string html)
Sanitizes the provided HTML fragment.
html
The sanitized HTML fragment.
Sanitize
expects a non-null rendered AppSurface Docs HTML fragment, not a complete document or unrendered template. Implementations should throw ArgumentNullException
when html
is null and should preserve already-encoded text rather than double-encoding it.
Harvests intentionally public JavaScript API doclets from policy-approved plain .js
source files.
The harvester is enabled by default through AppSurfaceDocsJavaScriptHarvestOptions.Enabled
and scans repository-relative JavaScript candidates that pass the shared harvest path policy. V1 is deliberately strict: broad discovery requires @public
, treats @internal
, @private
, and @ignore
as hard exclusions, skips file and directory reparse points before reads or descent, and turns unsupported public shapes into harvest diagnostics instead of partial docs.
Task<IReadOnlyList<DocNode>> HarvestAsync(string rootPath, CancellationToken cancellationToken = default)
Scans policy-approved JavaScript files under the repository root and returns generated AppSurface Docs API nodes.
rootPath
cancellationToken
Generated group pages plus fragment-addressable stub nodes for harvested JavaScript API items.
Task<IReadOnlyList<DocNode>> HarvestAsync(DocHarvestContext context, CancellationToken cancellationToken = default)
Scans JavaScript sources with the repository-scoped path policy captured for the current aggregation pass.
context
cancellationToken
Generated JavaScript API group pages and fragment-addressable API nodes.
This overload is used by the aggregator so VCS ignore exclusions are applied consistently across traversal and file inclusion checks. Custom harvesters continue to use the public HarvestAsync(string, CancellationToken)
contract.
bool IsValidEventDetailPropertyName(string value)
Validates whether a parsed @property
name is a supported event detail field contract.
value
true
when the member name represents a valid detail.*
path; otherwise false
.
The validator trims whitespace, strips optional JSDoc property wrappers through StripOptionalPropertyWrapper
, requires an ordinal detail.
prefix, and validates each remaining segment with IsValidEventDetailPropertySegment
. Array contracts use a trailing []
on a segment, such as detail.items[]
or detail.items[].id
. Common pitfalls are blank names, omitted detail.
prefixes, empty segments, unsupported characters, and assuming case-insensitive matching.
JavaScriptHarvestCandidate ClassifyHarvestCandidate(string rootPath, string candidatePath)
Classifies a JavaScript harvest candidate before the harvester reads a source file or descends into a directory.
rootPath
candidatePath
The candidate's normalized path metadata and safety state.
JavaScriptHarvestCandidate ClassifyHarvestCandidate(string rootPath, string candidatePath, Func<string, FileAttributes> getAttributes)
Classifies a JavaScript harvest candidate with a caller-supplied attribute reader for deterministic boundary tests.
rootPath
candidatePath
getAttributes
The candidate's normalized path metadata and safety state.
Captures the normalized path and boundary decision for a JavaScript harvest file-system candidate.
Status
FullPath
RelativePath
Provides stable helpers for host-owned AppSurface Docs RazorWire stream authorization.
Host applications that implement IRazorWireStreamAuthorizer
, or legacy IRazorWireChannelAuthorizer
compatibility policies, should use IsHarvestProgressChannel(string?)
when applying production authorization rules to the AppSurface Docs live harvest progress stream. Prefer the predicate over raw string comparison so future docs-owned stream naming remains centralized.
bool IsHarvestProgressChannel(string? channel)
Determines whether a RazorWire channel is the AppSurface Docs live harvest progress channel.
channel
true
when channel
exactly matches HarvestProgressChannel
or a valid named product channel returned by GetHarvestProgressChannel
; otherwise false
. Null, empty, malformed, and differently cased channel names do not match.
bool IsLegacyHarvestProgressChannel(string? channel)
Determines whether a RazorWire channel is the one legacy AppSurface Docs harvest-progress channel.
channel
true
only for an exact legacy Docs harvest-progress channel match.
Legacy Docs registration owns only HarvestProgressChannel
. Named Docs channels must be handled by AppSurfaceDocsNamedHarvestStreamAuthorizationFilter
; treating every named-looking channel as legacy Docs would override unrelated host channel policies that happen to use the same prefix.
string GetHarvestProgressChannel(string instanceName)
Builds the isolated harvest-progress channel name for one named Docs product.
instanceName
A stable, lowercase RazorWire-safe channel name for the supplied product.
ArgumentException
instanceName
is blank or is not a valid Docs product name.bool TryGetNamedInstanceFromHarvestProgressChannel(string? channel, out string? instanceName)
Attempts to read the Docs product name from a named harvest-progress channel.
channel
instanceName
true
when channel
is a named Docs harvest channel with a 1-64 character Docs product suffix; otherwise false
.
Rewrites harvested documentation links so authored Markdown can use repository-relative source links while the rendered docs experience still navigates through canonical AppSurface Docs routes.
string RewriteInternalDocLinks(string sourcePath, string html, string docsRootPath, DocLinkTargetManifest targetManifest)
Rewrites internal documentation anchors in rendered HTML so they point at canonical AppSurface Docs routes and carry Turbo navigation attributes that keep browser history aligned with frame navigation.
sourcePath
html
docsRootPath
targetManifest
The rewritten HTML fragment.
string PrefixPathBaseForDocsUrls(string html, string docsRootPath, string? requestPathBase, string routeRootPath = DocsUrlBuilder.DocsEntryPath)
Prefixes request PathBase
for rooted docs-local anchor hrefs in rendered HTML content.
html
docsRootPath
requestPathBase
routeRootPath
The original fragment when no path base applies or no docs-local rooted links are present; otherwise a fragment whose docs-local anchor hrefs are prefixed so mounted apps stay inside their virtual root.
This helper intentionally scopes itself to docs-local routes rather than all rooted links. Authored content may legitimately include other site-rooted links that should remain outside the docs shell, while docs-local links generated by RewriteInternalDocLinks(string,string,string,DocLinkTargetManifest)
must stay within the current mounted app.
Harvester implementation that scans Markdown source files and converts them into documentation nodes.
Task<IReadOnlyList<DocNode>> HarvestAsync(string rootPath, CancellationToken cancellationToken = default)
Harvests Markdown files under the specified root directory and converts each into a DocNode containing a display title, relative path, generated HTML, metadata, and page outline.
rootPath
cancellationToken
A collection of DocNode objects representing each processed Markdown source file, including the display title, path relative to rootPath
, generated HTML, metadata, and DocNode.Outline
entries when outline headings are available.
Skips files in excluded directories (for example "node_modules", "bin", "obj", and "Tests") and hidden dot-prefixed directories unless explicitly allowlisted. Dot-prefixed files are included. File and directory reparse points are skipped so symlinks and junctions cannot point the built-in harvester outside rootPath
. The root LICENSE
file is also included when present and not a reparse point so repository-relative license links can resolve in static exports. The special releases/unreleased.md
path loads and composes validated append-only entries from releases/unreleased.entries
before parsing and rendering. Because that rendered note is not byte-for-byte checked-in source, it is never retained for protected Markdown download. If a file's name is "README" (case-insensitive), its title is set to the parent directory name or "Home" for a repository root README. Before parsing, valid rich-authoring tabs render to placeholders, directive fences are normalized, and the generated tabs HTML replaces those placeholders. The resulting renderedMarkdownBody
is parsed once; HTML is rendered from that AST and DocNode.Outline
is populated from the same AST with ExtractOutline
, then filtered through the resolved Markdown outline policy so callers can rely on display outline data being present when eligible headings are available. DocNode.RichAuthoringTabsTokens
contains the generated tab tokens used by the trusted client runtime, while malformed rich-authoring directives remain literal and add harvest diagnostics available through IDocHarvesterDiagnosticProvider
. Files that fail to process are skipped and an error is logged.
Task<IReadOnlyList<DocNode>> HarvestAsync(DocHarvestContext context, CancellationToken cancellationToken = default)
Harvests Markdown files with the repository-scoped path policy captured for the current aggregation pass.
context
cancellationToken
Markdown documentation nodes generated from eligible repository files.
This overload is used by the aggregator so VCS ignore exclusions are applied consistently across traversal and file inclusion checks. Custom harvesters continue to use the public HarvestAsync(string, CancellationToken)
contract.
Task<MarkdownHarvestResult> HarvestWithSourceAsync(DocHarvestContext context, CancellationToken cancellationToken = default)
Harvests the built-in Markdown surface and, when enabled, retains eligible valid-UTF-8 source bytes for the aggregator's private download sidecar.
This internal result is intentionally separate from DocNode
so raw source never enters rendered HTML, search indexes, or the public harvester contract. The special releases/unreleased.md
source is composed with validated append-only entries before parsing and rendering, so it cannot expose a source-faithful download even when protected source capture is enabled. The byte-reader seam is used only for Markdown source capture; metadata sidecars and disabled downloads continue through the configured text reader.
bool TryDecodeValidUtf8(byte[] bytes, out string content)
Attempts a strict UTF-8 decode and falls back to replacement decoding.
bytes
content
false
, it contains the replacement-decoded content.
true
when bytes
is valid UTF-8; otherwise false
.
Task<DocMetadata?> ReadMetadataSidecarAsync(string markdownFilePath, string relativeMarkdownPath, CancellationToken cancellationToken, ICollection<DocHarvestDiagnostic>? harvestDiagnostics = null)
Reads an optional paired sidecar metadata file for a Markdown source document.
markdownFilePath
relativeMarkdownPath
cancellationToken
harvestDiagnostics
The parsed sidecar metadata, or null
when no valid sidecar applies.
AppSurface Docs supports paired metadata files named {file}.yml
and {file}.yaml
such as README.md.yml
. Reparse-point sidecars are ignored so metadata cannot be imported through a symlink or junction outside the harvest root. When both non-reparse extensions exist for the same Markdown file, AppSurface Docs logs a warning and ignores both sidecars until the ambiguity is removed. Inline front matter remains the primary metadata source and overrides any overlapping sidecar fields.
IReadOnlyList<DocOutlineItem> ExtractOutline(MarkdownDocument document)
Extracts page-local outline entries from Markdown heading blocks.
document
A source-ordered list of DocOutlineItem
values. Each item contains the rendered fragment DocOutlineItem.Id
, normalized reader-facing DocOutlineItem.Title
, and original heading DocOutlineItem.Level
.
Only HeadingBlock
descendants with levels between MinOutlineHeadingLevel
and MaxOutlineHeadingLevel
are included, which means the built-in Markdown harvester emits H2-H3 headings by default. Fragment IDs come from HtmlAttributesExtensions.GetAttributes(heading).Id
and titles are produced by NormalizeHeadingText(ExtractInlineText(heading.Inline))
. Headings without a non-empty fragment ID or normalized title are silently omitted; consumers and tests should account for those drops and for whitespace normalization when comparing outline titles.
string? ExtractLeadingTitle(MarkdownDocument document)
Extracts the document title from a leading Markdown H1 when one exists.
document
The normalized heading text from the leading H1, or null
when the document starts with another block or the H1 has no readable text.
This mirrors details-page H1 suppression: only the leading H1 can become package-owned page chrome. Later H1 elements remain body structure and do not replace filename or metadata title fallback behavior.
string ExtractInlineText(ContainerInline? inline)
Extracts plain reader-facing text from a Markdig inline container for outline display.
inline
The extracted text, or an empty string when no inline content exists.
string NormalizeHeadingText(string value)
Normalizes heading text by collapsing whitespace without introducing leading spaces.
value
The normalized heading text.
Private built-in Markdown harvest output used to retain source bytes beside the rendered Docs graph.
This type intentionally stays internal. Raw Markdown must not become part of DocNode
, the search index, or the public custom-harvester contract.
Registers the bounded rich-authoring directives that AppSurface Docs owns.
The extension deliberately builds on Markdig's fenced custom-container parser. The harvester first recognizes valid tabs and emits their complete server-rendered baseline; this extension then renders callouts, preserves generic custom containers, and leaves invalid rich directives visible as source markers with their body intact instead of guessing them into an interactive component.
Renders AppSurface Docs' package-owned rich-authoring custom containers.
Validates the deliberately small rich-authoring directive grammar and produces author diagnostics.
string NormalizeDirectiveFences(string markdown)
Normalizes package directives to Markdig's generic custom-container fence shape without changing authored code.
markdown
Markdown whose supported directive opening fences have the parser-required separator.
Markdig's generic custom-container extension recognizes ::: callout
, while AppSurface Docs deliberately exposes the compact :::callout
authoring grammar. The conversion is limited to actual Markdown lines and skips fenced code so syntax examples continue to render as literal code.
AppSurfaceDocsRichAuthoringTabsRenderResult RenderValidTabs(string markdown, string sourcePath, Func<string, string> renderPanelMarkdown)
Replaces valid package tabs with fixed server-rendered HTML before Markdig parses the surrounding Markdown.
markdown
sourcePath
renderPanelMarkdown
A source-safe replacement plan for valid tabs and their complete server-rendered source-order baseline.
Markdig custom containers intentionally do not nest containers with an identical author-facing fence. AppSurface Docs keeps the compact uniform :::
grammar by recognizing the bounded tabs structure before invoking Markdig, then delegates each panel's ordinary Markdown back to the same pipeline. Invalid groups are left untouched so the generic rich-authoring fallback remains visible and diagnostic-producing.
Holds valid tabs rendered into placeholders so directive normalization never reprocesses their generated HTML.
Associates one source-safe tabs placeholder with its generated server HTML.
Describes the result of validating one custom container against the rich-authoring grammar.
Captures one rule evaluation step for internal harvest path diagnostics.
Code
Scope
global
, Markdown
, CSharp
, or default-allow
.Pattern
DefaultGroup
Matched
SourcePath
LineNumber
Exposes non-fatal diagnostics captured by a harvester during its most recent successful run.
The aggregate health snapshot reads these diagnostics only after the harvester participates in the current snapshot. Failed, timed-out, canceled, or disabled harvesters surface through the primary harvester-health diagnostic instead.
IReadOnlyList<DocHarvestDiagnostic> GetHarvestDiagnostics()
Gets the diagnostics captured during the most recent completed harvester run.
Structured diagnostics suitable for inclusion in the aggregate harvest-health snapshot.
Validates document paths carried by published AppSurface Docs search-index payloads.
Published search indexes are archive metadata, not a general URL surface. Archive payloads must store canonical /docs
-rooted document paths so the published-tree rewriter can safely rebase them for aliases, exact versions, custom route roots, and request path bases at serve time. The served-path entry point is a defense-in-depth check for already-rebased browser links; it must not be used to validate immutable archive contents.
PublishedSearchIndexPathValidationResult ValidateArchivePath(string? value, PublishedSearchIndexArchivePathContext context)
Validates a path stored in an exact published release tree's search-index.json
.
value
documents[*].path
value.context
A structured validation result whose PublishedSearchIndexPathValidationResult.Reason
identifies the first rejected condition, or PublishedSearchIndexPathRejectionReason.None
when the archive value is safe to store.
Archive validation is intentionally stricter than served-link validation: stored paths must use canonical /docs/...
forms and must not include request path bases, custom route roots, origins, or deployment aliases. The checks run from syntax and URL-shape hazards toward docs-root and version-family hazards. When several rejection reasons apply, callers should log or surface only the returned first reason plus PublishedSearchIndexPathValidationResult.RedactedValue
; do not log the original value.
PublishedSearchIndexPathValidationResult ValidateRecommendationArchivePath(string? value, PublishedSearchIndexArchivePathContext context)
Validates a nested recommendation URL stored in an immutable release archive.
value
context
A canonical stable- /docs
route and its validated fragment, or a redacted rejection.
Recommendation paths always store the stable export route, even when the top-level document-path policy accepts an already-versioned path for compatibility. The original value is passed through that existing policy first so URL shape, origin, suffix encoding, traversal, and reserved-route checks run before the query is discarded.
PublishedSearchIndexPathValidationResult ValidateServedPath(string? value, PublishedSearchIndexServedPathContext context)
Validates a browser-visible search result path after published-tree rewriting has applied the active docs root.
value
context
A structured validation result whose PublishedSearchIndexPathValidationResult.NormalizedPath
is safe to use as a browser-visible link only when PublishedSearchIndexPathValidationResult.IsValid
is true
.
Served validation accepts the active docs root and optional archive root after route rewriting has already happened. It still rejects executable schemes, off-root links, traversal, encoded separators, controls, and reserved docs endpoints before the value can enter client-side result rendering.
string ToDiagnosticCode(PublishedSearchIndexPathRejectionReason reason)
Converts a rejection reason to the stable lower-kebab diagnostic code used in logs, telemetry, and tests.
reason
One of none
, missing
, whitespace
, not-root-relative
, scheme-url
, absolute-url
, protocol-relative
, backslash
, control-character
, malformed-percent-encoding
, encoded-separator
, encoded-traversal
, outside-docs-root
, reserved-route
, wrong-version
, or unknown
for future enum values.
Use PublishedSearchIndexPathRejectionReason
for code branching and this string only for stable diagnostics that may cross process, log, or test boundaries.
Immutable context for validating document paths stored in a published exact-version archive.
Version
Runtime context for validating already-rebased browser-visible search result paths.
DocsRootPath
ArchiveRootPath
Structured result for a published search-index document path validation attempt.
IsValid
Reason
PublishedSearchIndexPathRejectionReason.None
when valid. Use PublishedSearchIndexDocumentPathPolicy.ToDiagnosticCode(PublishedSearchIndexPathRejectionReason)
when a lower-kebab telemetry or log value is required. NormalizedPath
ValidatedFragment
#
, when one was supplied.RedactedValue
PublishedSearchIndexPathValidationResult Valid(string normalizedPath, string? validatedFragment = null)
Creates a successful validation result for a normalized path-only value.
normalizedPath
validatedFragment
#
, or null
when none was supplied.
A valid result with PublishedSearchIndexPathRejectionReason.None
.
PublishedSearchIndexPathValidationResult Invalid(PublishedSearchIndexPathRejectionReason reason, string redactedValue)
Creates a rejected validation result with a stable reason and redacted original value.
reason
redactedValue
An invalid result whose NormalizedPath
is null
.
Highlights Markdown code fences behind AppSurface Docs' internal HTML contract.
Use this abstraction when Markdown rendering needs package-owned code HTML without coupling callers to a specific highlighter implementation. Implementations must return HTML-safe output for direct insertion into docs rendering templates, including escaped plaintext fallback for unsupported languages or failed highlighting.
AppSurfaceDocsHighlightedCode Highlight(AppSurfaceDocsCodeBlock block)
Renders a code block as either highlighted token markup or escaped plaintext fallback.
block
AppSurface Docs-owned code block HTML. Callers treat the returned value as immutable render output and insert it without additional escaping.
ArgumentNullException
block
is null
.Process-local, bounded aggregate read model for hosted AppSurface Docs search-quality review.
This service accepts only validated, sanitized product-intelligence events. It stores no raw event payloads, raw search text, URLs, identity, cookies, request bodies, or free-form comments. The rolling window exists only to bound process memory while preserving enough recent aggregate signal for maintainer diagnostics.
void Record(AppSurfaceProductEventContract contract, IReadOnlyDictionary<string, string> properties)
Records one sanitized docs product-intelligence event into the bounded aggregate model.
contract
properties
AppSurfaceDocsSearchQualityResponse GetSnapshot(AppSurfaceDocsOptions options)
Creates a maintainer-facing snapshot of the current aggregate model.
options
A defensive aggregate snapshot.
Owns Markdown code-fence language normalization, safe CSS class suffixes, and TextMateSharp lookup ids.
AppSurfaceDocsCodeLanguage Normalize(string? language)
Normalizes an authored language token into AppSurface Docs' stable language contract.
language
A safe language descriptor for rendering and TextMate lookup.
string CreateSafeClassSlug(string value)
Converts arbitrary language input into a CSS-safe lowercase ASCII slug.
value
A lowercase slug containing only ASCII letters, digits, and hyphens.
Coordinates shared AppSurface Docs harvest work so startup warmup, first requests, and trusted operator rebuilds use one ordered source-backed loop.
Task<DocHarvestHealthSnapshot> EnsureStarted()
Starts or reuses the shared initial harvest task.
The memoized harvest-health task for the current run. A new task is created when no task exists or when the prior task was canceled or faulted.
Callers share one background harvest through this coordinator. The task itself runs with CancellationToken.None
so one impatient request cannot cancel warmup for later requests.
ValueTask<AppSurfaceDocsHarvestRebuildRequestResult> RequestRebuildAsync(CancellationToken cancellationToken)
Requests a trusted operator rebuild of the full source-backed docs harvest.
cancellationToken
AppSurfaceDocsHarvestRebuildRequestResult.Started
when a fresh rebuild started immediately, AppSurfaceDocsHarvestRebuildRequestResult.Queued
when the active run will be followed by one rebuild, or AppSurfaceDocsHarvestRebuildRequestResult.AlreadyQueued
when a rebuild was already pending.
The shared harvest itself runs with CancellationToken.None
. Canceling the operator request cannot cancel a harvest already visible to other docs requests. When a rebuild is queued behind an active run, the active run's completion visit is suppressed so only the superseding rebuild returns the browser to the verified docs context.
Task<bool> WaitForCompletionAsync(TimeSpan waitBudget, CancellationToken cancellationToken)
Waits for the shared initial harvest to complete within the provided wait budget.
waitBudget
false
immediately.cancellationToken
true
when the harvest task completes within budget; otherwise false
.
The caller's token cancels only the wait, not the shared harvest task. Exceptions from the harvest task are observed when the task completes before the timeout.
bool IsFatalHarvestException(Exception exception)
Determines whether a queued rebuild continuation should avoid catching an exception that represents process-level failure rather than recoverable harvest failure.
exception
true
for process-fatal exception types; otherwise false
.
AppSurfaceDocsHarvestProgressSnapshot CurrentProgress { get; }
Source
Gets the latest redacted harvest progress snapshot published by the reporter.
int CompletionDelay { get; }
Source
Gets the completion-navigation delay, in milliseconds, used by the progress reporter.
bool HasActiveOrQueuedHarvest { get; }
Source
Gets a value indicating whether a harvest is running or a queued rebuild is waiting for the running harvest.
Enumerates the documentation targets harvested into an AppSurface Docs snapshot so link rewriting can avoid guessing from file extensions alone.
The manifest stores both source paths, such as guides/start.md
, and canonical browser paths, such as guides/start.md.html
. Query strings and fragments are intentionally ignored because anchors and query parameters decorate a page target rather than defining a separate harvested document.
DocLinkTargetManifest FromNodes(IEnumerable<DocNode> nodes)
Creates a manifest from harvested documentation nodes.
nodes
A manifest containing source and canonical target forms for the supplied nodes.
DocLinkTargetManifest FromPaths(IEnumerable<string?> paths)
Creates a manifest from source or canonical documentation paths.
paths
A manifest containing normalized source and canonical target forms.
bool Contains(string? path)
Determines whether the supplied path resolves to a harvested documentation target.
path
true
when the normalized target is in the manifest; otherwise false
.
Sanitizes harvested AppSurface Docs HTML with the package-owned allowlist for docs content and highlighted code blocks.
AppSurface Docs starts from the HtmlSanitizer defaults, adds the package-owned content tags section
, article
, header
, details
, summary
, pre
, code
, and span
, and allows the class
, id
, open
, role
, aria-label
, and package-owned rich-authoring and code data-*
attributes. The sanitizer explicitly removes style
from the default attribute set so harvested Markdown, generated API HTML, and server-side highlighted code can keep structural hooks while inline presentation and unsafe markup are stripped. Callers should pass already-rendered AppSurface Docs HTML through this sanitizer before display or export; supported semantic wrappers and token spans are preserved, while scripts, event handlers, inline styles, and unsupported attributes are discarded.
string Sanitize(string html)
Sanitizes rendered documentation HTML using the AppSurface Docs allowlist.
html
Safe HTML that preserves AppSurface Docs structural markup and removes unsupported tags or attributes.
Provides one package-owned harvester with a redacted, run-scoped progress reporting surface.
This internal session accepts only a closed phase enum and numeric document deltas. It deliberately cannot carry a file name, path, source text, exception, percentage, or arbitrary activity string. Custom IDocHarvester
implementations never receive this type and retain the established status-only progress contract.
ValueTask TransitionAsync(AppSurfaceDocsHarvestProgressPhase phase)
Records a safe parser lifecycle transition.
phase
A task that completes after the transition is retained and a live publication is scheduled.
This method does not throw for an ignored transition. The server-issued progress identity prevents one harvester from mutating another harvester's state.
ValueTask ReportSourceUnitAsync(int documentsFoundDelta)
Records one inspected source unit and an optional output delta.
documentsFoundDelta
A task that completes after the delta is recorded and any configured test pacing has elapsed.
ArgumentOutOfRangeException
documentsFoundDelta
is negative.OperationCanceledException
A positive output delta is paced one document at a time only when the local test delay is configured. The delay follows the real report that found those documents; source units that yield no documents are never delayed.
ValueTask ReportOutputOnlyAsync(int documentsFoundDelta)
Records materialized output that is not attributable to one newly inspected source unit.
documentsFoundDelta
A task that completes after the delta is recorded and any configured test pacing has elapsed.
ArgumentOutOfRangeException
documentsFoundDelta
is negative.OperationCanceledException
Zero is valid and is not paced. Negative values throw ArgumentOutOfRangeException
from the reporter. Only positive deltas are delayed, so reporting a source unit that produces no documents never slows a harvester.
Starts the optional AppSurface Docs harvest warmup and performs the strict harvest-health startup preflight.
The service is always registered by AddAppSurfaceDocs()
. By default it starts the same memoized harvest used by docs requests through their shared AppSurfaceDocsHarvestCoordinator
. Blocking and strict startup await that same task, so completed warmup is immediately visible to requests even with a zero request-wait budget. Strict mode fails startup only when the aggregate snapshot is failed.
Task StartAsync(CancellationToken cancellationToken)
Checks harvest health during host startup when strict harvest failure is enabled.
cancellationToken
A completed task when strict mode is disabled or the aggregate status is not failed.
AppSurfaceDocsHarvestFailedException
AppSurfaceDocsHarvestOptions.FailOnFailure
is enabled and the aggregate harvest status is DocHarvestHealthStatus.Failed
. Task StopAsync(CancellationToken cancellationToken)
Stops the preflight service.
cancellationToken
A completed task because the preflight owns no background work.
Task<DocHarvestHealthSnapshot> EnsureHarvestStarted()
Shares request readiness when available, preserving hosts that remove the optional coordinator.
Captures locale identity, grouping, and diagnostics for one docs snapshot.
Enabled
DefaultLocale
null
when disabled or unavailable.DocSets
VariantsBySourcePath
Diagnostics
The graph is the Phase 1 localization handoff between harvesters, route identity, navigation, fallback, and search projection code. Consumers should use this graph instead of re-inferring locale state from source paths.
Groups localized variants that represent the same conceptual documentation page.
TranslationKey
DefaultLocaleSourcePath
null
when missing.Variants
FallbackMode
Describes one resolved localized document variant.
SourcePath
Locale
TranslationKey
Title
PublicRoutePath
null
when unavailable.LocaleFallback
LocaleWasInferred
TranslationKeyWasInferred
Locale and translation key may be authored in metadata, inferred from a configured filename suffix, inferred from a locale folder when a translation key is authored, or defaulted to the configured default locale. Public route paths are null when route identity rejected the source path.
Builds the locale-aware document graph used by later route, navigation, fallback, and search projections.
This Phase 1 builder is intentionally internal. It records document identity and locale facts without changing the existing visible route or search behavior. Later slices should consume this graph instead of re-inferring locale state in controllers, views, or JavaScript.
LocalizedDocsGraph Build(IEnumerable<DocNode> docs, DocRouteIdentityCatalog routeIdentityCatalog)
Builds the localized graph for a docs snapshot.
docs
routeIdentityCatalog
A disabled empty graph when localization is off, otherwise the resolved localization graph.
The builder skips fragment stub source paths, reports unsupported locale signals, duplicate variants, missing bases, folder conflicts, disabled fallback gaps, and conflicting fallback overrides as diagnostics, then returns whatever safe graph data it can derive.
Resolves normalized AppSurface Docs identity options into render-ready browser chrome values.
The resolved identity intentionally stores only app-relative or app-root paths. Razor views apply the current request path base at render time with Url.PathBaseAware(...)
, so singleton identity resolution stays safe for virtual-directory deployments and tests that render the same service provider under multiple path bases.
AppSurfaceDocsResolvedIdentity Identity { get; }
Source
Gets the render-ready identity used by AppSurface Docs layouts.
Render-ready AppSurface Docs identity.
DisplayName
HomeHref
Logo
Favicons
string? WordmarkHighlightText { get; init; }
Source
Gets the first display-name substring rendered with highlight treatment by the built-in docs chrome.
Null means the wordmark is rendered as plain text. The value is already trimmed and confirmed to appear in DisplayName
, so Razor views can split the display name without repeating configuration policy.
string? WordmarkHighlightColor { get; init; }
Source
Gets the CSS hex color used for WordmarkHighlightText
.
Null keeps highlighted text in the surrounding wordmark color. Non-null values have already passed the AppSurface Docs CSS hex color allowlist.
Render-ready AppSurface Docs logo.
Path
AltText
Render-ready AppSurface Docs favicon entry.
Path
Type
(string Markdown, DocMetadata? Metadata) Extract(string markdown)
Extracts inline Markdown front matter and returns the remaining Markdown with parsed metadata.
markdown
A tuple containing the Markdown body and parsed DocMetadata
when present and valid.
This compatibility wrapper discards parser diagnostics. Invalid inline YAML returns the original Markdown with null
metadata, and non-fatal authoring warnings such as invalid curation YAML or migration metadata are intentionally not surfaced. Call ExtractWithDiagnostics
when callers need warnings.
(string Markdown, MarkdownMetadataParseResult Result) ExtractWithDiagnostics(string markdown)
Extracts inline Markdown front matter and returns the remaining Markdown with diagnostics-aware metadata.
markdown
A tuple containing the Markdown body and a MarkdownMetadataParseResult
whose MarkdownMetadataParseResult.Metadata
contains parsed DocMetadata
when present.
This is the authoritative internal entry point for inline metadata parsing. Missing front matter returns the original Markdown and an empty diagnostic list. Invalid inline YAML returns a AppSurfaceDocsMetadataDiagnostic
instead of throwing, and deliberately preserves the original Markdown so a malformed header remains visible to the reader. Callers should inspect MarkdownMetadataParseResult.Diagnostics
for authoring warnings instead of relying on exceptions for inline metadata failures.
DocMetadata? ParseMetadataYaml(string yaml)
Parses a YAML metadata document into normalized documentation metadata.
yaml
The normalized metadata model, or null
when the YAML document is empty or explicitly null.
YamlException
yaml
cannot be parsed as YAML.
This compatibility wrapper is shared by inline Markdown front matter and paired sidecar metadata files so both authoring styles normalize through the same schema, defaults, and empty-list handling. It returns only the MarkdownMetadataParseResult.Metadata
value from ParseMetadataYamlWithDiagnostics(string)
and intentionally discards schema, migration, and authoring diagnostics. Call ParseMetadataYamlWithDiagnostics(string)
when callers need those warnings in addition to normalized DocMetadata
.
MarkdownMetadataParseResult ParseMetadataYamlWithDiagnostics(string yaml)
Parses a YAML metadata document into a diagnostics-aware metadata result.
yaml
A MarkdownMetadataParseResult
containing optional normalized DocMetadata
plus any AppSurfaceDocsMetadataDiagnostic
warnings produced while normalizing supported metadata fields.
This is the authoritative internal entry point for metadata documents that are already known to be YAML, including sidecar files. Empty documents and explicit YAML null
values return null
metadata and no diagnostics. An empty mapping literal such as {}
still produces a normalized DocMetadata
instance whose fields may all be null
. YAML syntax errors still throw YamlException
so sidecar callers can report the sidecar file failure through their existing error path; schema and migration warnings are returned through MarkdownMetadataParseResult.Diagnostics
.
MarkdownDownloadEligibility GetMarkdownDownloadEligibility(string markdown)
Determines whether inline front matter explicitly opts a Markdown document into protected source download.
markdown
A value that is eligible only for the exact top-level plain declaration download_markdown: true
. A present declaration with another shape is marked invalid so harvest health can guide the document author.
This intentionally does not use general metadata binding or paired sidecars. Download eligibility is a security declaration: quoted strings, nested fields, duplicate declarations, alternative casing, and truthy-looking values must not accidentally expose raw source.
Enforces AppSurface Docs' reserved harvest-stream gate before host RazorWire stream authorizers run.
This filter protects the docs-owned harvest progress channel even when a host registers an IRazorWireStreamAuthorizer
after AddAppSurfaceDocs()
and thereby replaces the normal Docs wrapper in Microsoft DI. The filter only gates the reserved AppSurface Docs channel; non-docs channels continue to the host authorizer unchanged.
ValueTask<AppSurfaceAuthResult?> AuthorizeAsync(RazorWireStreamAuthorizationContext context)
Applies hidden-route and shared read-policy checks to the AppSurface Docs harvest progress channel.
context
null
for non-docs channels or when the normal Docs wrapper is already active; otherwise a gate result that denies hidden routes or read-policy failures and lets host authorizers narrow successful reads.
Applies AppSurface Docs harvest path rules for source-backed Markdown, C#, JavaScript, and Python documentation.
Policy order is intentionally fixed: built-in source candidates are checked first, then global includes, source-specific includes, default exclusion groups and their allows, repository VCS ignore rules when a snapshot supplies them, global excludes, and source-specific excludes. Default groups protect build output, hidden directories, test projects, and C# source under examples
. Directory pruning uses the same defaults and clear /**
subtree excludes, but keeps a default-excluded subtree only when a configured group allow can match that directory or one of its descendants.
AppSurfaceDocsHarvestPathPolicy CreateDefault()
Creates a policy with package defaults and no configured include or exclude globs.
AppSurfaceDocsHarvestPathDecision Evaluate(string relativePath, AppSurfaceDocsHarvestSourceKind sourceKind)
Evaluates a repository-relative path and returns the include/exclude decision with rule trace details.
The input must be a normalized relative candidate. Invalid paths are excluded with AppSurfaceDocsHarvestPathDecisionCode.ExcludedByInvalidPath
. Include misses use the Miss
codes, while configured exclude and default-group denials use their corresponding ExcludedBy*
codes.
bool ShouldIncludeFilePath(string relativePath, AppSurfaceDocsHarvestSourceKind sourceKind)
Returns whether relativePath
is included by the path evaluator.
IEnumerable<string> EnumerateCandidateFiles(string rootPath, AppSurfaceDocsHarvestSourceKind sourceKind, string searchPattern, CancellationToken cancellationToken)
Enumerates candidate files under rootPath
while pruning policy-excluded subtrees.
The searchPattern
is applied to each visited directory. File and directory reparse points are skipped before they can be harvested or traversed, so symlinks and junctions cannot point built-in harvesters outside the selected repository root. Cancellation is observed between directory visits.
bool ShouldPruneDirectory(string relativeDirectory, AppSurfaceDocsHarvestSourceKind sourceKind)
Returns whether a normalized repository-relative directory can be skipped during traversal.
Invalid directories are pruned. Default-excluded directories are pruned unless the matched group has an allow glob that can apply to a file inside the directory or a descendant. Configured subtree excludes prune only when a /**
pattern matches the directory.
bool IsKnownDefaultGroupId(string? groupId)
Returns whether groupId
is a supported named default exclusion group.
Matching is case-insensitive but name-only; numeric enum values are rejected so configuration stays stable.
string NormalizeDefaultGroupId(string? groupId)
Normalizes a named default exclusion group to canonical casing, or returns the trimmed input when unsupported.
Evaluates normalized repository-relative paths against ordered harvest glob patterns.
Matching is case-insensitive. MatchFirst
is order-dependent and returns the first configured pattern that matches the candidate. Directory helpers are conservative because pruning must never skip a file that a later allow pattern could include; callers should validate and normalize paths before invoking the matcher.
string? MatchFirst(string relativePath)
Returns the first configured pattern that matches relativePath
, or null when none match.
string? MatchDirectorySubtree(string relativeDirectory)
Returns the first /**
subtree pattern that matches relativeDirectory
itself.
The matcher probes a sentinel child path under the directory. This keeps clear subtree excludes fast, but patterns that do not end in /**
are ignored because they may describe only files or a narrower leaf match.
string? MatchDirectoryOrDescendantSubtree(string relativeDirectory)
Returns the first /**
pattern that could match the directory or one of its descendants.
string? MatchDirectoryOrDescendant(string relativeDirectory)
Returns the first pattern that could match a file inside relativeDirectory
or a descendant.
This is intentionally broader than MatchDirectoryOrDescendantSubtree
so file-level allow globs such as .github/workflows/*.yml
keep the containing default-excluded directories enumerable.
string? MatchFileInDirectoryOrDescendant(string relativeDirectory)
Returns the first pattern that could match a file directly inside relativeDirectory
or below one of its descendants.
Unlike MatchDirectoryOrDescendant
, this helper is allowed to rule out nested directories when the remaining glob pattern can only match a file in the current directory, such as src/public*.js
. Harvesters use it to avoid walking subtrees that cannot contribute matching files.
bool HasPatterns { get; }
Source
Gets a value indicating whether any patterns were configured.
Wraps a single configured glob pattern and exposes case-insensitive match helpers.
bool Matches(string relativePath)
Returns whether relativePath
matches Pattern
.
bool MatchesDirectoryOrDescendant(string relativeDirectory)
Returns whether Pattern
can apply to the directory or any descendant path.
bool CouldMatchDirectoryOrDescendant(string relativeDirectory)
Returns whether Pattern
could match any file under relativeDirectory
.
bool CouldMatchFileInDirectoryOrDescendant(string relativeDirectory)
Returns whether Pattern
could match a file under relativeDirectory
.
string Pattern { get; }
Source
Gets the original configured pattern.
Builds canonical AppSurface Docs URLs for one AppSurface Docs route family.
This builder centralizes the route contract so controllers, view components, views, and client scripts do not each guess how the docs surface is rooted. RouteRootPath
is the stable route-family root used for archive and exact-version routes. CurrentDocsRootPath
is the live source-backed docs root used for current docs, search, and current search-index routes. Most consumers should copy Routes
rather than assembling route strings or calling lower-level builder methods directly.
string BuildHomeUrl()
string BuildSearchUrl()
Builds the current live docs search workspace URL.
The app-relative search workspace URL for the current docs surface.
string BuildSearchIndexUrl()
Builds the current live docs search-index URL.
The app-relative search-index URL for the current docs surface.
string BuildSearchIndexRefreshUrl()
Builds the current live docs search-index refresh URL.
The app-relative operator refresh route for the current docs search index. Callers must send SearchIndexRefreshMethod
with a valid MVC anti-forgery token and satisfy the host-configured AppSurface Docs search-index refresh policy.
string BuildHarvestUrl()
Builds the current live docs harvest observatory URL.
The app-relative operator harvest observatory URL for the current docs surface.
string BuildHarvestRebuildUrl()
Builds the current live docs harvest rebuild URL.
The app-relative operator rebuild route for the current docs harvest. Callers must send HarvestRebuildMethod
with a valid MVC anti-forgery token and satisfy the host-configured AppSurface Docs operator-write policy.
string BuildHealthUrl()
Builds the current live docs harvest health HTML URL.
The app-relative health page URL for the current docs surface.
string BuildHealthJsonUrl()
Builds the current live docs harvest health JSON URL.
The app-relative machine-readable health URL for the current docs surface.
string BuildRouteInspectorUrl()
Builds the current live docs route inspector HTML URL.
The app-relative route inspector URL for the current docs surface.
string BuildRouteInspectorJsonUrl()
Builds the current live docs route inspector JSON URL.
The app-relative machine-readable route inspector URL for the current docs surface.
string BuildMetricsCollectUrl()
Builds the current live docs metrics collection URL.
The app-relative browser metrics ingestion URL for the current docs surface.
string BuildSearchQualityUrl()
Builds the current live docs search-quality diagnostics URL.
The app-relative search-quality diagnostics URL for the current docs surface.
string BuildSectionUrl(DocPublicSection section)
Builds a current-surface public section URL.
section
The canonical section URL rooted at the current docs surface.
string BuildDocUrl(string path)
Builds a current-surface canonical document URL.
path
The canonical document URL rooted at the current docs surface.
string BuildDocUrl(string docsRootPath, string path)
Builds a canonical document URL rooted at an explicit docs surface root.
docsRootPath
path
The canonical document URL.
string BuildMarkdownDownloadUrl(string path)
Builds the protected Markdown attachment route for one canonical non-root Docs path.
path
An app-relative, segment-encoded Markdown download URL.
This method intentionally accepts only a clean canonical route path. It rejects aliases, source-shaped paths, traversal segments, separators that would change route identity, and the docs home so link rendering cannot create an address that the protected download endpoint will later reject.
string BuildAssetUrl(string assetName)
Builds the current-surface search asset URL.
assetName
search.css
.The canonical asset URL rooted at the current docs surface.
string BuildVersionRootUrl(string version)
Builds the exact-version root URL for one published docs release.
version
The canonical root URL for that version.
string BuildVersionDocUrl(string version, string path)
Builds a canonical document URL rooted at a specific exact version.
version
path
The canonical document URL rooted at the requested version.
string BuildAliasRootUrl(string name)
Builds the root URL for one named exact-version alias.
name
The alias root under this route family, such as /docs/a/stable
.
ArgumentNullException
null
.ArgumentException
This method creates a URL only; it does not establish that a matching public alias is configured or available. Alias names are lowercased invariantly and allow ASCII letters and digits at their edges, with dot, underscore, and hyphen also allowed internally. Slashes, percent escapes, whitespace, and dot segments are rejected.
string BuildAliasDocUrl(string name, string path)
Builds an alias-local document URL.
name
BuildAliasRootUrl(string)
.path
The document URL rooted at the normalized alias route.
ArgumentNullException
null
.ArgumentException
Path encoding follows BuildVersionDocUrl(string, string)
.
string BuildCanonicalHref(string appRelativeCanonicalUrl)
Builds the browser-facing canonical href for an app-relative canonical route.
appRelativeCanonicalUrl
/docs/start
.
The app-relative canonical route when no public origin is configured, or an absolute public canonical URL when PublicOrigin
is set.
AppSurface Docs keeps route identity app-relative until the final render boundary. This method is that boundary for canonical metadata: it joins the configured origin with the already-selected canonical path without changing current, preview, archive, or exact-version route semantics.
string BuildVersionsUrl()
bool IsCurrentDocsPath(string? path)
Determines whether the supplied request path is inside the current live docs surface.
path
true
when the path belongs to the current live docs surface; otherwise false
.
string? NormalizePublicOriginOrNull(string? publicOrigin)
Normalizes a configured public origin for absolute canonical metadata.
publicOrigin
The normalized origin, or null
when the value is blank.
ArgumentException
bool TryNormalizePublicOrigin(string? publicOrigin, out string? normalizedPublicOrigin)
Attempts to normalize a configured public origin for absolute canonical metadata.
publicOrigin
normalizedPublicOrigin
null
when the value is blank.
true
when the value is blank or a valid HTTP(S) origin; otherwise false
.
bool IsUnderRoot(string? path, string docsRootPath)
Determines whether a request path belongs to the supplied docs root.
path
docsRootPath
true
when path
resolves to the docs root itself or one of its child routes; otherwise false
.
Blank paths always return false
. Root-mounted docs ( /
) use IsLikelyRootMountedDocsPath(string)
so only known docs-like routes are treated as current docs traffic. Non-root mounts use case-insensitive exact and prefix matching against {docsRootPath}/...
.
string JoinPath(string docsRootPath, string relativePath)
Joins a normalized docs root with a relative docs route segment.
docsRootPath
relativePath
The combined app-relative route path.
Leading slashes on relativePath
are ignored. null
, empty, and whitespace-only relative paths return the docs root unchanged. When the docs root is /
, the result stays root-mounted instead of producing a doubled slash. Callers are expected to pass already-normalized root paths and docs-relative segments rather than arbitrary URLs.
string NormalizeDocsRootPath(string? docsRootPath, bool versioningEnabled)
Normalizes a configured docs root into the app-relative route contract AppSurface Docs uses at runtime.
docsRootPath
versioningEnabled
/docs/next
.The normalized app-relative docs root path.
string NormalizeRouteRootPath(string? routeRootPath, string docsRootPath, bool versioningEnabled)
Normalizes a configured route-family root into the app-relative route contract AppSurface Docs uses at runtime.
routeRootPath
docsRootPath
versioningEnabled
/docs
.The normalized app-relative route-family root path.
bool VersioningEnabled { get; }
Source
Gets a value indicating whether versioning is enabled for the current host.
string CurrentDocsRootPath { get; }
Source
Gets the canonical root path for the current live source-backed docs surface.
string RouteRootPath { get; }
Source
Gets the stable route-family root for this AppSurface Docs instance.
The route root is the parent for the stable entry alias, version archive, and exact-version release trees. It is the same as CurrentDocsRootPath
when versioning is disabled, and commonly the parent of the live preview root when versioning is enabled. For example, RouteRootPath=/foo/bar
with DocsRootPath=/foo/bar/next
keeps the archive at /foo/bar/versions
while the live preview stays at /foo/bar/next
.
string DocsEntryRootPath { get; }
Source
Gets the docs entry path used as the stable public landing alias.
string DocsVersionPrefixPath { get; }
Source
Gets the stable exact-version prefix for this route family.
string DocsVersionsRootPath { get; }
Source
Gets the stable archive path for this route family.
AppSurfaceDocsRouteReferences Routes { get; }
Source
Gets named AppSurface Docs routes that consumers should prefer over hardcoded route strings.
string? PublicOrigin { get; }
Source
Gets the configured public origin used for absolute canonical metadata, or null
when unset.
This value is an origin only, for example https://docs.example.com
. It never includes the AppSurface Docs route root because canonical route identity is still owned by BuildDocUrl(string)
, BuildVersionDocUrl(string, string)
, and the route manifest.
Named AppSurface Docs routes for one configured route family.
Consumers should prefer this record when they need well-known AppSurface Docs destinations in host code, operator guidance, generated configuration, or documentation. The values are app-relative. Views and other presentation boundaries apply request PathBase
separately before sending browser-facing URLs.
void Deconstruct(out string home, out string search, out string searchIndex, out string searchIndexRefresh, out string versions)
Deconstructs the original route set for callers that used the positional record contract.
home
search
searchIndex
searchIndexRefresh
versions
void Deconstruct(out string home, out string search, out string searchIndex, out string searchIndexRefresh, out string versions, out string health, out string healthJson)
Deconstructs the route set through harvest health diagnostics.
home
search
searchIndex
searchIndexRefresh
versions
health
healthJson
void Deconstruct(out string home, out string search, out string searchIndex, out string searchIndexRefresh, out string versions, out string health, out string healthJson, out string routeInspector, out string routeInspectorJson)
Deconstructs all known routes including diagnostics routes.
home
search
searchIndex
searchIndexRefresh
versions
health
healthJson
routeInspector
routeInspectorJson
void Deconstruct(out string home, out string search, out string searchIndex, out string searchIndexRefresh, out string versions, out string harvest, out string harvestRebuild, out string health, out string healthJson, out string routeInspector, out string routeInspectorJson)
Deconstructs all known routes including harvest rebuild and diagnostics routes.
home
search
searchIndex
searchIndexRefresh
versions
harvest
harvestRebuild
health
healthJson
routeInspector
routeInspectorJson
string Home { get; init; }
Source
Gets the current live docs home route.
string Search { get; init; }
Source
Gets the current live docs search workspace route.
string SearchIndex { get; init; }
Source
Gets the current live docs search-index JSON route.
string SearchIndexRefresh { get; init; }
Source
Gets the authenticated search-index refresh route.
string SearchIndexRefreshMethod { get; init; }
Source
Gets the HTTP method callers must use with SearchIndexRefresh
.
string Harvest { get; init; }
Source
Gets the current live docs harvest observatory route.
string HarvestRebuild { get; init; }
Source
Gets the authenticated harvest rebuild route.
string HarvestRebuildMethod { get; init; }
Source
Gets the HTTP method callers must use with HarvestRebuild
.
string Versions { get; init; }
Source
Gets the route-family archive route, whether or not versioning endpoints are currently enabled.
string Health { get; init; }
Source
Gets the current live docs harvest health HTML route.
string HealthJson { get; init; }
Source
Gets the current live docs harvest health JSON route.
string RouteInspector { get; init; }
Source
Gets the current live docs route inspector HTML route.
string RouteInspectorJson { get; init; }
Source
Gets the current live docs route inspector JSON route.
string MetricsCollect { get; init; }
Source
Gets the current live docs metrics collection route.
string SearchQuality { get; init; }
Source
Gets the current live docs search-quality diagnostics route.
Contains AppSurface Docs-owned HTML for a rendered Markdown code block.
Html
NormalizedLanguage
IsHighlighted
Describes AppSurface Docs' normalized view of an authored code-fence language token.
NormalizedLanguage
ClassLanguage
language-*
class.Label
TextMateLanguageId
null
for plaintext fallback.IsKnown
IsPlainText
Publishes the public route identity graph for one AppSurface Docs snapshot.
The manifest is an internal read model, not a second router. It contains only public canonical winners plus redirect aliases that should recover to those winners. Collision losers, reserved routes, and invalid routes stay represented by diagnostics so export and future consumers do not guess a destination for ambiguous paths.
Describes one public AppSurface Docs page and the aliases that should redirect to it.
SourcePath
CanonicalRoutePath
CanonicalLiveUrl
RecoveryAliases
DeclaredAliases
SourcePathIsMarkdown
SourcePath
is a Markdown document.Describes one route alias that redirects to a canonical AppSurface Docs page.
RoutePath
LiveUrl
Kind
Applies Markdown display-outline rules after metadata defaults and author overrides have been resolved.
IReadOnlyList<DocOutlineItem> Apply(IReadOnlyList<DocOutlineItem> outline, DocMetadata? metadata)
Applies explicit outline metadata and automatic repeated-heading suppression to a harvested Markdown outline.
outline
metadata
The outline entries to expose to readers and search heading metadata.
This method filters the display outline only. The rendered Markdown HTML remains unchanged, so fragment links to hidden outline headings can still resolve when readers or search results point directly at the heading.
Harvester implementation that scans C# source files for XML documentation comments.
Task<IReadOnlyList<DocNode>> HarvestAsync(string rootPath, CancellationToken cancellationToken = default)
Collects XML documentation from C# source files under the specified root and produces DocNode entries containing titles, relative file paths with anchors, and HTML-formatted content.
rootPath
cancellationToken
A collection of DocNode objects; each contains a title, a relative file path including a fragment anchor, and the extracted HTML documentation.
Skips files in excluded directories (for example "node_modules", "bin", "obj", "Tests", and "examples") and hidden dot-prefixed directories unless explicitly allowlisted. Dot-prefixed files are included. File and directory reparse points are skipped so symlinks and junctions cannot point the built-in harvester outside rootPath
.
Task<IReadOnlyList<DocNode>> HarvestAsync(DocHarvestContext context, CancellationToken cancellationToken = default)
Collects XML documentation with the repository-scoped path policy captured for the current aggregation pass.
context
cancellationToken
A collection of generated C# API documentation nodes.
This overload is used by the aggregator so VCS ignore exclusions are applied consistently across traversal and file inclusion checks. Custom harvesters continue to use the public HarvestAsync(string, CancellationToken)
contract.
Task<IReadOnlyList<DocNode>> HarvestTypedAsync(string rootPath, IHarvestPathPolicy pathPolicy, AppSurfaceDocsHarvestProgressSession? progress, CancellationToken cancellationToken)
Harvests built-in C# namespace pages into the internal semantic projection consumed by Razor.
This is intentionally reachable only through the exact built-in aggregation overload. The public overload above continues to call the legacy HTML compatibility serializer so existing IDocHarvester
consumers and derived harvesters retain their established contract.
string GetMethodId(MethodDeclarationSyntax method, string qualifiedTypeName)
Computes the safe ID for a method to be used in HTML content and stub nodes.
method
qualifiedTypeName
The safe ID string for the method documentation section.
string GetPropertyId(PropertyDeclarationSyntax property, string qualifiedTypeName)
Computes the safe ID for a property to be used in HTML content and stub nodes.
property
qualifiedTypeName
The safe ID string for the property documentation section.
string GetHighlightedDisplaySignature(MethodDeclarationSyntax method)
Generates a syntax-highlighted HTML string representing a method signature for display.
method
An HTML fragment containing the highlighted signature.
string GetHighlightedPropertySignature(PropertyDeclarationSyntax property)
Generates a syntax-highlighted HTML string representing a property signature for display.
property
An HTML fragment containing the highlighted signature.
string GetPropertyAccessorSignature(PropertyDeclarationSyntax property)
Computes the accessors (get/set/init) for a property as a string for inclusion in signatures.
property
A string like "{ get; set; }" or "{ get; }".
void AppendHighlightedParameter(StringBuilder builder, ParameterSyntax parameter)
Appends a syntax-highlighted parameter declaration to the provided StringBuilder.
builder
parameter
string GetDisplayTypeName(TypeDeclarationSyntax typeDecl)
Gets the display name for a type declaration, including generic type parameter placeholders (e.g., <T>).
typeDecl
The display name string.
string GetTypeNameForQualifiedId(TypeDeclarationSyntax typeDecl)
Gets the type name for a qualified ID, appending backtick arity for generic types (e.g., MyType`1).
typeDecl
The type name string used in safe IDs.
bool IsCompilerGeneratedCallerParameter(ParameterSyntax parameter)
Determines whether a parameter is a compiler-generated caller information parameter (for example, [CallerFilePath]).
parameter
true
if the parameter should be hidden from documentation; otherwise, false
.
string? ExtractDoc(SyntaxNode node, string relativePath, ICollection<DocHarvestDiagnostic> diagnostics)
Extracts XML documentation from the leading trivia of a syntax node and converts it into HTML fragments.
node
relativePath
diagnostics
The HTML string containing structured documentation sections, or null
if no documentation is present or parsing fails.
void AppendTextSection(StringBuilder html, string cssClass, XElement? section, string? heading = null)
Appends a simple text section (like summary or remarks) to the HTML builder.
html
cssClass
section
heading
void AppendNamedListSection(StringBuilder html, string cssClass, string heading, IEnumerable<XElement> entries, Func<XElement, string?> keySelector)
Appends a list of named entries (like parameters or exceptions) to the HTML builder.
html
cssClass
heading
entries
keySelector
string RenderBlockContent(XElement element)
Renders the content of an XElement as block-level HTML (wrapping in paragraphs if necessary).
element
An HTML fragment string.
string RenderInlineContent(XElement element)
Renders the content of an XElement as inline HTML.
element
An HTML fragment string.
string RenderNodes(IEnumerable<XNode> nodes, bool inlineContext)
Renders a collection of XML nodes into HTML strings.
nodes
inlineContext
The combined HTML string.
string RenderNode(XNode node, bool inlineContext)
Renders a single XML node into its corresponding HTML fragment.
node
inlineContext
The HTML fragment string.
string NormalizeWhitespace(string value)
Normalizes whitespace in the provided string by replacing all whitespace sequences with a single space.
value
The normalized string.
void AddOutlineItem(NamespaceDocPage namespacePage, string title, string id, int level)
Adds an outline item to a namespace page when the entry is complete and its target ID has not already been recorded.
namespacePage
title
id
level
string? SimplifyCref(string? cref)
Simplifies a "cref" attribute value by removing the type prefix (e.g., "M:", "T:").
cref
The simplified string, or null
if the input was empty.
NamespaceDocPage GetOrCreateNamespacePage(IDictionary<string, NamespaceDocPage> namespacePages, string namespaceName)
Gets an existing NamespaceDocPage
for the specified namespace name, or creates a new one if it doesn't exist.
namespacePages
namespaceName
The retrieved or newly created page.
void EnsureNamespaceHierarchy(IDictionary<string, NamespaceDocPage> namespacePages)
Builds the hierarchical structure for namespaces, ensuring parent pages exist and child links are added back into the content. Rebuilds namespacePages
in place keyed by NamespaceDocPage.Path
.
namespacePages
string GetNamespaceName(SyntaxNode node)
Extracts the dotted namespace name for a given syntax node by traversing its ancestors.
node
The full dotted namespace name, or "Global" if none is found.
string BuildNamespaceDocPath(string namespaceName)
Constructs the relative documentation route path for a given namespace name.
namespaceName
The relative route path string (e.g., "Namespaces/MyNamespace").
string GetNamespaceTitle(string fullNamespace)
Derives a display title for a namespace name.
fullNamespace
The display title; returns the last segment of the namespace or "Namespaces" for the root.
string GetParentNamespace(string namespaceName)
Gets the parent namespace name for a dotted namespace string.
namespaceName
The parent namespace name, or an empty string if it is a root namespace.
string GetQualifiedName(BaseTypeDeclarationSyntax node)
Builds the dot-delimited qualified name for a type or enum declaration, including enclosing types and namespaces.
node
The qualified name as a dot-delimited string containing nested type and namespace segments.
Represents a single documentation page for a C# namespace, accumulating content from types within it.
Authorizes the AppSurface Docs harvest progress stream with result-bearing RazorWire authorization semantics.
Use this wrapper when AppSurface Docs owns the harvest-progress channel but must preserve host RazorWire authorization for other channels. The harvest decision order is: harvest route visibility, configured shared diagnostics read policy, optional custom host authorizer narrowing, Development fallback, compatibility custom authorizers, then deny. Built-in RazorWire allow-all and deny-all authorizers are compatibility defaults and do not authorize the Docs harvest stream in non-Development hosts.
ValueTask<AppSurfaceAuthResult> AuthorizeAsync(RazorWireStreamAuthorizationContext context)
Authorizes the requested Docs or host stream channel.
context
A passive AppSurface auth result for the stream subscription.
Builds normalized AppSurface Docs metadata defaults and fallbacks for harvested documentation nodes.
DocMetadata CreateMarkdownMetadata(string path, string resolvedTitle, DocMetadata? explicitMetadata, string? derivedSummary)
Creates normalized metadata for a Markdown documentation node without emitting normalization warnings.
path
resolvedTitle
explicitMetadata
derivedSummary
The merged metadata with inferred defaults, normalized nav-group handling, and fallback breadcrumbs.
DocMetadata CreateMarkdownMetadata(string path, string resolvedTitle, DocMetadata? explicitMetadata, string? derivedSummary, ILogger? logger)
Creates normalized metadata for a Markdown documentation node and optionally logs authored nav-group fallback warnings.
path
resolvedTitle
explicitMetadata
derivedSummary
logger
nav_group
values do not resolve to a built-in public section and AppSurface Docs falls back to the derived section assignment. The merged metadata with normalized section labels, fallback breadcrumbs, and derived-field flags.
This shared internal entry point normalizes explicit public-section selection, preserves authored metadata where valid, derives title/summary fallback semantics, and rebuilds default breadcrumbs when authors do not supply them explicitly.
DocMetadata CreateApiReferenceMetadata(string title, string namespaceName)
Creates canonical metadata for an API-reference documentation node.
title
namespaceName
Metadata configured for API-reference navigation, contributor visibility, and namespace breadcrumbs.
string? DeriveComponentFromPath(string path)
Derives the owning AppSurface component name from a documentation path when possible.
path
The inferred component name, or null
when no component hint can be derived.
string? DeriveComponentFromNamespace(string namespaceName)
Derives the owning AppSurface component name from a namespace.
namespaceName
The inferred component name, or null
when the namespace is blank.
Loads, validates, and writes the frozen route manifest stored inside exported exact-version docs trees.
Frozen manifests are archive-local read models. They preserve the route identity that existed when an exact release tree was exported, but they do not replace DocRouteIdentityCatalog
for live source-backed docs. New exports also bind every logical canonical identity to an ordinary HTML artifact beneath the complete export root and declare htmlUrlBase: export-root
. Legacy v1 documents without these optional fields retain logical redirects and docs-relative HTML rewriting. Partial mappings, unsafe paths, unfinished exporter staging, and route namespace collisions disable the entire new manifest; verified archive loading rejects them before activation.
Task WriteAsync(string outputPath, AppSurfaceDocsRouteManifest routeManifest, CancellationToken cancellationToken)
Writes the frozen route manifest artifact to an export output directory.
outputPath
routeManifest
cancellationToken
A task that completes once the manifest has been written.
string Serialize(AppSurfaceDocsRouteManifest routeManifest)
Serializes a frozen route manifest document only after strict validation succeeds.
routeManifest
The exact JSON payload used for the frozen route manifest artifact.
ArgumentNullException
routeManifest
is null
.InvalidOperationException
This writer-facing API validates with the same strict rules used for exact archive pins. It throws instead of dropping unsafe entries when a canonical route is missing or unsafe, when aliases are unsafe, self-referential, or collide with canonical routes, or when duplicate aliases point at different canonical routes. Use it when creating a new frozen manifest from trusted source-backed route metadata. Use the tolerant loading paths when reading an existing archive where an invalid manifest should degrade to an empty alias map instead of failing the caller.
string SerializeForExport(AppSurfaceDocsRouteManifest routeManifest)
Stages live canonical URLs for exporter finalization before release-manifest hashing.
routeManifest
Strictly validated route JSON containing private exportCanonicalLiveUrl
members.
This is an exporter handoff, not a consumable archive. The exporter must replace every staging member with the successful ordinary HTML outcome's whole-root canonicalArtifactPath
and add htmlUrlBase: export-root
before integrity hashing. Final archive loading rejects leftover staging data. Use Serialize
for legacy logical-route fixtures that do not undergo this finalization.
string BuildManifestPath(string outputPath, string fileName)
Builds the on-disk path for a frozen route manifest filename beneath an exact-version export root.
outputPath
fileName
outputPath
.The manifest path under the export output root.
AppSurfaceDocsFrozenRouteManifest Load(IFileProvider fileProvider, ILogger logger, string sourceDescription)
Loads a frozen manifest from a mounted exact-version tree provider.
fileProvider
logger
sourceDescription
The parsed manifest, or Empty
when the manifest is missing or unusable.
bool TryLoadVerified(byte[] utf8Bytes, out AppSurfaceDocsFrozenRouteManifest manifest, out string issue)
Parses verified frozen route manifest bytes that have already matched a catalog-pinned release archive manifest.
utf8Bytes
manifest
issue
true
when the verified bytes describe a supported frozen route manifest.
bool TryResolveAlias(string aliasRoutePath, out string canonicalRoutePath)
Attempts to resolve a docs-root-relative alias route to its frozen canonical route path.
aliasRoutePath
canonicalRoutePath
true
when the alias is known by the frozen manifest; otherwise false
.
bool TryResolveCanonicalArtifactPath(string canonicalRoutePath, out string artifactPath)
Resolves a logical canonical identity to its finalized archive HTML member and canonical fragment.
canonicalRoutePath
artifactPath
Whether this archive supplies a finalized mapping for the identity.
bool IsSafeRoutePath(string? routePath)
Checks whether a docs-root-relative route path is safe to use as a frozen alias or redirect target.
routePath
true
when the route stays inside the docs archive namespace; otherwise false
.
AppSurfaceDocsFrozenRouteManifest CreateSnapshot(FrozenRouteManifestDocument document, IReadOnlyDictionary<string, string> aliases, IReadOnlyDictionary<string, string> artifacts, bool htmlUsesExportRootUrls)
Keeps complete route identities even for a valid manifest with no redirects.
IReadOnlyList<string> PublicRoutePaths { get; set; }
Source
Gets canonical, source-shaped recovery and declared routes captured from verified bytes.
The snapshot owns a read-only copy; consumers cannot change the routes shared by mounted aliases.
bool HtmlUsesExportRootUrls { get; }
Source
Whether HTML URLs are relative to the complete export root rather than the legacy logical docs root.
IReadOnlyCollection<string> CanonicalArtifactPaths { get; }
Source
Gets the ordinary HTML members that release verification must bind to this same archive.
AppSurfaceDocsFrozenRouteManifest Empty { get; }
Source
Gets the empty manifest used when an archive has no frozen route identity or when parsing failed.
Caches the frozen route manifest for one mounted exact-version tree.
AppSurfaceDocsFrozenRouteManifest GetManifest(ILogger logger)
Returns the cached manifest, loading it from the tree on first use.
logger
The cached frozen route manifest, or an empty manifest when unavailable.
bool UsesVerifiedSnapshot { get; }
Source
Gets a value indicating whether this cache is backed by manifest data parsed during release archive verification.
Provides file-system traversal helpers for source-backed AppSurface Docs harvesting.
Built-in harvesters treat the configured repository root as the read boundary. Candidate traversal therefore skips file and directory reparse points before a harvester can read content through a symlink, junction, or similar filesystem indirection. The helper preserves the existing lazy depth-first traversal shape and lets callers provide their own repository-relative directory-pruning policy.
IEnumerable<string> EnumerateCandidateFiles(string rootPath, string searchPattern, Func<string, bool> shouldPruneDirectory, CancellationToken cancellationToken)
Lazily enumerates candidate files under a repository root while skipping reparse-point files and directories.
rootPath
searchPattern
shouldPruneDirectory
cancellationToken
Absolute file paths that match searchPattern
and are not reparse points.
File-system enumeration and attribute exceptions intentionally flow to callers, matching the existing harvester behavior for unreadable trees. This keeps operational failures visible instead of silently shrinking the public documentation surface.
bool IsNonReparsePointFile(string filePath)
Returns whether filePath
exists and is not a file-system reparse point.
filePath
true
when the file exists and can be read as a normal source file candidate; otherwise false
.
Use this for explicit one-off source reads such as root LICENSE
files and Markdown sidecars that do not flow through candidate traversal. Missing files return false
. Attribute lookup exceptions still flow so callers do not accidentally hide filesystem failures.
Validates physical paths that belong to the AppSurface Docs trusted release store.
The guard is intentionally filesystem-backed and fail-closed. AppSurface Docs uses it before mounting published release trees and before reading request-time files from a mounted tree so catalog metadata cannot redirect a public docs route outside the operator-owned release store.
string NormalizePhysicalPath(string path)
Converts a filesystem path to a full physical path and removes a trailing directory separator.
path
Path.GetFullPath(string)
.The canonical physical path without a trailing directory separator.
string ResolveConfiguredRoot(string contentRootPath, string? configuredRootPath, string catalogDirectory)
Resolves the trusted release root from configuration, defaulting to the catalog directory when unset.
contentRootPath
configuredRootPath
catalogDirectory
The canonical trusted release root path.
string ResolveContentRootRelativePath(string contentRootPath, string configuredPath)
Resolves an operator-configured path, preserving rooted paths and anchoring relative paths under the content root.
contentRootPath
configuredPath
The full filesystem path represented by configuredPath
.
bool TryResolveCatalogTreePath(string trustedReleaseRootPath, string? configuredExactTreePath, out string? exactTreePath, out string? publicIssue, out string? internalDetail)
Resolves a catalog exactTreePath
under the trusted release root after rejecting unsafe metadata.
trustedReleaseRootPath
configuredExactTreePath
exactTreePath
publicIssue
internalDetail
true
when the catalog path is safe to validate under the trusted root; otherwise, false
.
bool TryValidateDirectory(string directoryPath, string publicMissingIssue, string publicUnsafeIssue, out string? publicIssue, out string? internalDetail)
Validates that a physical directory exists and is not itself a symlink, junction, or reparse point.
directoryPath
publicMissingIssue
publicUnsafeIssue
publicIssue
internalDetail
true
when the directory exists and is ordinary; otherwise, false
.
bool TryValidateFileCandidate(string exactTreeRootPath, string relativeFilePath, out string physicalFilePath, out string? denialReason)
Resolves and validates a file candidate beneath an exact release tree root.
exactTreeRootPath
relativeFilePath
physicalFilePath
denialReason
true
when the file candidate stays under the tree and has no reparse segments; otherwise, false
.
bool TryValidateNoReparseSegments(string trustedRootPath, string candidatePath, bool expectLeafFile, out string? denialReason)
Walks a candidate path from its trusted root and rejects any symlink, junction, or reparse point segment.
trustedRootPath
candidatePath
.candidatePath
expectLeafFile
denialReason
true
when every segment from root to candidate is ordinary; otherwise, false
.
bool IsSameOrDescendant(string trustedRootPath, string candidatePath)
Determines whether a canonical candidate path is equal to or physically beneath a trusted root path.
trustedRootPath
candidatePath
true
when the candidate equals the root or starts below it using platform path comparison semantics.
bool IsPathMetadataException(Exception ex)
Classifies exceptions that can occur while normalizing paths or reading filesystem metadata.
ex
true
when callers should convert the exception into a fail-closed validation denial.
bool TryValidateSegment(string path, bool expectFile, out string? denialReason)
Validates one physical path segment as an ordinary file or directory.
path
expectFile
denialReason
true
when the segment exists and is not a link or reparse point; otherwise, false
.
bool IsLinkOrReparsePoint(FileSystemInfo info)
Detects whether a filesystem entry is a symlink, junction, or other reparse point.
info
true
when the entry has reparse attributes or a link target.
bool ContainsParentTraversal(string path)
Checks catalog metadata for parent-directory traversal segments.
path
true
when any path segment is exactly ..
.
bool ContainsHiddenSegment(string path)
Checks catalog metadata for hidden release tree segments while allowing a leading current-directory marker.
path
true
when any non-current-directory segment starts with .
.
StringComparer PhysicalPathComparer { get; }
Source
Gets the comparer used for canonical physical paths on the current platform.
StringComparison PhysicalPathComparison { get; }
Source
Gets the comparison mode used when checking whether one canonical physical path contains another.
Cached search-index payload for the live source-backed docs surface.
Metadata
Documents
Metadata emitted with each docs search-index payload.
GeneratedAtUtc
Version
Engine
Search document entry emitted for the built-in docs search experience.
Id
Path
Title
Summary
Headings
BodyText
Snippet
PageType
PageTypeLabel
PageTypeVariant
Audience
Component
Aliases
Keywords
Status
NavGroup
PublicSection
PublicSectionLabel
IsSectionLanding
Order
SequenceKey
CanonicalSlug
RelatedPages
Breadcrumbs
SourcePath
EntryPoints
Language
LanguageLabel
SummaryPresentation
ApiLifecycle
public
, alpha
, or beta
. Omitted for all other documents.ApiLifecycleLabel
ApiLifecycle
: Public API
, Alpha
, or Beta
. Omitted for all other documents.IsDeprecated
true
is emitted only with generated-symbol metadata; false
and missing values are omitted for other documents.IsGeneratedApiSymbol
true
marker emitted only for validated, provenanced built-in generated API fragments. Consumers must not infer lifecycle from ordinary page metadata.
The Path
value is cached relative to the live docs surface root and can be rebased onto a request PathBase
at response time without rebuilding the full snapshot. Lists are serialized as JSON arrays so the browser client can preserve exact ordering for headings, aliases, related pages, and breadcrumbs.
IReadOnlyList<DocsSearchIndexRecommendation> RecommendedPages { get; init; }
Source
Gets complete authored-first next reads, including nonsearch targets; old indexes may omit this member.
A complete JSON next-read row. TargetId is the stable canonical identity (including an approved fragment); Path is surface-specific. Source is explicitly authored/automatic. Consumers need no documents-array lookup and should use generic presentation for future optional explanation or badge values. Old indexes treat a missing list as empty.
Resolved sequence and authored links owned by one snapshot; public projections detach every row.
A bounded, display-only Markdown projection for a docs search-result summary.
Kind
text
, strong
, emphasis
, or code
.Text
text
and code
nodes.Children
strong
and emphasis
nodes.
This representation intentionally exposes only text, strong, emphasis, and code nodes. It is not an HTML or hyperlink transport and is kept separate from DocsSearchIndexDocument.Summary
so existing consumers retain the raw summary text they use for ranking or custom presentation.
Search projection for one namespace README entry point.
Label
Summary
Target
Href
Keywords
Describes a requested search-index projection for the cached docs snapshot.
Locale
IncludeAllLocales
Caches search-index payloads projected from one immutable docs snapshot.
Phase 1 always returns the default payload, but the cache reserves normalized per-locale keys so later slices can compute locale-specific payloads without changing DocAggregator
callers. Access to the mutable projection dictionary is guarded by a private lock, and cache growth is capped because projection values can come from requests.
DocsSearchIndexPayload GetPayload(DocsSearchIndexProjection projection)
Gets the cached payload for a normalized projection.
projection
The default payload in Phase 1, or a cached projection payload in later localization slices.
When localization is disabled, or when the projection has no locale, the default payload is returned without growing the projection cache. During Phase 1, locale projections also return the default payload; the cache entry is a bounded placeholder for later locale-specific payload generation.
DocsSearchIndexProjection NormalizeProjection(DocsSearchIndexProjection projection)
Normalizes a projection key before cache lookup.
projection
A projection whose locale is null for blank input, or trimmed and lower-case invariant otherwise.
int CachedProjectionCount { get; }
Source
Gets the number of seeded projection entries, exposed so tests can verify the cache bound without reflection.
Private source bytes and canonical identity returned by the current Docs snapshot for an authorized Markdown download.
This is intentionally internal: controllers may turn the bytes into a protected attachment, but callers cannot use it as a general raw-content API and it never participates in DocNode
serialization or search.
Service responsible for aggregating documentation from multiple harvesters and caching the results.
Task<IReadOnlyList<DocNode>> GetDocsAsync(CancellationToken cancellationToken = default)
Retrieves all harvested documentation nodes sorted by their Path.
cancellationToken
A read-only list of all DocNode
objects ordered by their Path.
Task<DocHarvestHealthSnapshot> GetHarvestHealthAsync(CancellationToken cancellationToken = default)
Returns structured health for the current AppSurface Docs harvest snapshot.
cancellationToken
Structured harvest health that distinguishes valid empty docs from failed or degraded harvests.
The health snapshot is produced by the same memoized harvest used by GetDocsAsync(CancellationToken)
. If no docs snapshot exists yet, calling this method triggers the same snapshot generation as a docs read. Caller cancellation cancels only the caller's wait; it does not cancel or poison the shared snapshot computation.
Task<DocNode?> GetDocByPathAsync(string path, CancellationToken cancellationToken = default)
Retrieves a documentation node for a source path or canonical docs path.
path
cancellationToken
The matching DocNode
, or null
if no node exists for the given path.
The lookup awaits the cached docs snapshot, then delegates to the snapshot's DocPathResolver
so legacy source paths, generated canonical .html
paths, fragments, separators, and casing follow the same matching rules used by details pages and curated links.
Task<DocRouteResolution> ResolvePublicRouteAsync(string path, CancellationToken cancellationToken = default)
Resolves a requested browser-facing docs route against the current snapshot route catalog.
path
packages
, a rooted docs path such as /docs/packages
, or a source-shaped path. Markdown source-shaped paths for public winners resolve as redirects to their clean public routes; non-Markdown source paths, collision losers, and reserved routes remain non-public. cancellationToken
A DocRouteResolution
whose kind tells callers whether the request is the canonical public route, a declared or Markdown source-shaped alias that should redirect to DocRouteResolution.PublicRoutePath
, an internal non-Markdown source match, a collision or reserved-route loser, or an unresolved path.
This method does not redirect or mutate the snapshot. It awaits GetCachedDocsSnapshotAsync
, then delegates to DocRouteIdentityCatalog.ResolvePublicRoute(string)
so controllers and link builders branch on the same route identity semantics. Markdown source-shaped redirects let links copied from GitHub or editor paths recover to their published canonical routes instead of falling into the generic 404 page.
Task<MarkdownDownloadSource?> GetMarkdownDownloadSourceAsync(string path, CancellationToken cancellationToken = default)
Retrieves source-faithful Markdown bytes for one exact canonical public route in the current Docs snapshot.
Raw source stays private to the snapshot and is returned only for built-in Markdown documents that explicitly opted in during harvest. Aliases, source-shaped paths, generated documents, the root landing page, and missing source entries return null
rather than exposing repository identity.
Task<AppSurfaceDocsRouteManifest> GetRouteManifestAsync(CancellationToken cancellationToken = default)
Gets the route manifest for the current cached docs snapshot.
cancellationToken
The final public route manifest derived from the same catalog used for live docs routing.
The manifest is produced from the final route identity catalog after namespace README merging and duplicate path resolution. Export consumes this in-process so it can write source-shaped redirect artifacts without crawling an HTTP manifest endpoint or duplicating route rules.
Task<DocDetailsViewModel?> GetDocDetailsAsync(string path, CancellationToken cancellationToken = default)
Builds the typed details view model for the specified documentation page.
path
cancellationToken
A DocDetailsViewModel
containing the resolved page, its in-page outline, and wayfinding links, or null
when the page cannot be resolved.
Task<DocsSearchIndexPayload> GetSearchIndexPayloadAsync(CancellationToken cancellationToken = default)
Returns the docs search-index payload generated during docs aggregation.
cancellationToken
A typed payload containing the search metadata and documents emitted by the live docs surface. The payload is cached before response serialization so callers can rebase rooted paths, such as /docs/guide.html
, onto a request PathBase
without reparsing or reserializing an intermediate JSON node graph.
Task<DocsSearchIndexPayload> GetSearchIndexPayloadAsync(DocsSearchIndexProjection projection, CancellationToken cancellationToken = default)
Returns a cached search-index projection for future locale-aware search consumers.
projection
cancellationToken
The matching search payload. Phase 1 preserves the existing payload schema for every projection while reserving the snapshot-owned cache seam that localized search will fill in Phase 3.
Task<IReadOnlyList<DocSectionSnapshot>> GetPublicSectionsAsync(CancellationToken cancellationToken = default)
Returns the normalized public-section snapshots derived from the harvested docs corpus.
cancellationToken
The ordered public sections visible in the current docs snapshot.
Task<DocSectionSnapshot?> GetPublicSectionAsync(DocPublicSection section, CancellationToken cancellationToken = default)
Returns one normalized public-section snapshot when the section is present in the current docs snapshot.
section
cancellationToken
The matching section snapshot, or null
when the section has no visible public pages.
void InvalidateCache()
Invalidates the cached docs snapshot so docs and search-index are rebuilt on next access.
Task<CachedDocsSnapshot> GetCachedDocsSnapshotAsync()
Retrieves the cached docs snapshot, harvesting docs and generating the search-index payload when absent.
A cached snapshot containing both docs and search-index payload.
When harvesting, each active harvester is invoked; failures from individual harvesters are caught and logged. Contents are sanitized before being cached. If multiple nodes share the same Path, a warning is logged and the first occurrence is retained. The search-index payload is generated from the same harvested snapshot. Caller cancellation does not cancel shared snapshot computation; callers can cancel their own wait. Harvester execution is bounded by a timeout so a single slow harvester cannot block snapshot regeneration indefinitely. The memoized cache entry is created with the configured absolute expiration from AppSurfaceDocsOptions.CacheExpirationMinutes
.
Task<T> AwaitHarvesterResultOrTimeoutAsync<T>(Task<T> harvesterTask, CancellationToken timeoutToken)
Awaits one harvester task while giving a completed result precedence when it races the timeout cancellation.
The shared timeout token cancels both the harvester and this wait. Once the wait returns a result, callers must preserve it rather than re-reading the timeout token: that token can transition after a valid result crossed the boundary. A task that has not completed when cancellation wins is classified by the caller as timed out.
Dictionary<string, DocNode> ResolveTypedNamespaceEntryPointHrefs(IReadOnlyDictionary<string, DocNode> docsByPath, DocRouteIdentityCatalog routeIdentityCatalog)
Resolves docs-local namespace entry-point hrefs in the built-in typed C# projection against the final route identity catalog.
Namespace README metadata is authored before route identity is available and can therefore use a source-shaped generated C# path. The typed renderer must receive a canonical browser URL directly: unlike legacy HTML, its Razor output is never passed through DocContentLinkRewriter
. Fragment entry points stay local to the page; app-relative destinations must resolve to a known route beneath the active Docs root before Razor sees them. This prevents trusted metadata from turning the internal typed rendering path into a same-origin navigation escape hatch.
Task<DateTimeOffset?> ResolveGitLastUpdatedUtcAsync(string repositoryRoot, string sourcePath, ILogger logger, CancellationToken cancellationToken, Func<string, IReadOnlyList<string>, string, ILogger, CancellationToken, Task<CommandResult>>? executeProcessAsync = null)
Resolves the last committed UTC timestamp for a source path from local git history.
repositoryRoot
sourcePath
logger
cancellationToken
executeProcessAsync
The exact last-updated UTC timestamp when git returns a parseable ISO 8601 commit date; otherwise null
.
IReadOnlyList<DocSectionSnapshot> BuildPublicSections(IEnumerable<DocNode> docs, ILogger logger)
Builds the public-section snapshots from the harvested docs corpus.
docs
logger
The ordered public sections that have at least one visible page.
(DocsSearchIndexPayload Payload, int RecordCount) BuildSearchIndexPayload(IEnumerable<DocNode> docs, IReadOnlyList<DocSectionSnapshot> publicSections, DocRouteIdentityCatalog routeIdentityCatalog, DocRecommendationPolicyResult recommendations)
Builds the search-index payload from the harvested documentation nodes.
docs
publicSections
routeIdentityCatalog
recommendations
A tuple containing the serializable payload and the number of records indexed.
string NormalizeSearchText(string? text)
Decodes HTML entities and normalizes whitespace in the provided text for search indexing.
text
The normalized text.
bool ShouldUseSearchSnippetForRichAuthoringSummary(string content, string? summary)
Determines whether a rendered rich-authoring page must use its reader-facing snippet instead of a raw Markdown summary.
content
summary
true
when the summary contains rich-authoring fence syntax for content that rendered successfully; otherwise, false
.
Invalid directives intentionally render as literal source and retain their authored markers. This guard therefore requires both a raw fence in the summary and package-rendered rich markup before it substitutes the already normalized snippet.
string BuildSearchDocUrl(string path)
Constructs a browser-facing URL for a documentation path.
path
A URL string starting with "/docs".
string BuildSearchDocUrl(string docsRootPath, string path)
Constructs a browser-facing URL for a documentation path rooted at a specific docs surface.
docsRootPath
path
A URL string rooted at docsRootPath
.
string TruncateSnippetAtWordBoundary(string text, int maxLength)
Truncates a text snippet at the last word boundary before the maximum length is exceeded.
text
maxLength
The truncated text with an ellipsis if it was shortened.
(IReadOnlyDictionary<string, DocWayfindingSnapshot> Wayfinding, DocRecommendationPolicyResult Recommendations) BuildWayfindingSnapshot(IReadOnlyList<DocNode> docs, DocPathResolver resolver, IReadOnlyList<DocSectionSnapshot> sections)
Resolves all legacy wayfinding and new recommendations once after merge, canonical collision resolution and section landing selection. A shared canonical link map supplies sequence neighbors and policy facts; authored destinations are projected separately. Their title fallback index is created once on demand within this build. Response projections detach links. Results publish atomically with the search projection in the cached generation.
DocsSearchIndexPayload DetachRecommendations(DocsSearchIndexPayload payload)
Detaches the new nested mutable collections without changing the locale graph or cached ranking.
Task<DocRecommendationMeasurements> GetRecommendationMeasurementsAsync(CancellationToken cancellationToken = default)
Returns build-time candidate counts without exposing the snapshot or a request-time ranking operation.
IReadOnlyDictionary<string, DocNode> BuildRelatedTitleLookup(IReadOnlyList<DocNode> docs)
Indexes readable authored destinations by display title, preserving the related-page resolver's order/title/path winner and stable input ordering for ties. The build-local lookup is populated only when route resolution fails.
IReadOnlyList<DocHarvestDiagnostic> MergeNamespaceReadmes(List<DocNode> nodes, string repositoryRoot, bool renderEntryPointPanel, ILogger logger)
Merges authored namespace-intro content into the corresponding namespace overview pages.
nodes
NAMESPACE.md
sources are removed from this list, and unresolved NAMESPACE.md
sources are hidden after diagnostics are recorded. repositoryRoot
NAMESPACE.md
intros.renderEntryPointPanel
logger
Non-fatal harvest diagnostics produced while merging authored namespace-intro metadata.
string MergeNamespaceIntroIntoContent(string namespaceContent, string readmeContent)
Inserts README content into a namespace overview page after the auto-generated namespace groups.
namespaceContent
readmeContent
The merged HTML content, with any leading README H1 omitted from the namespace intro section.
int FindMatchingSectionEnd(string content, int sectionStart)
Finds the index of the closing </section> tag that matches a <section> tag starting at the specified index.
content
sectionStart
The index of the closing tag, or -1 if no match is found.
bool IsReadmePath(string path)
Determines whether the specified path points to a documentation README file.
path
true
if the path identifies a README.md file; otherwise, false
.
string ExtractNamespaceNameFromNamespacePath(string path)
Extracts the dotted namespace name from a documentation path under the "Namespaces/" directory.
path
The extracted namespace name.
string? ExtractNamespaceNameFromReadmePath(string path)
Attempts to extract a namespace name from a README path by looking at the parent directory name.
path
The extracted namespace name, or null
if it cannot be determined.
string? ExtractNamespaceNameFromReadmePath(string path, IEnumerable<string>? knownNamespaceNames)
Extracts a namespace name from a README path, optionally matching against a list of known namespaces.
path
knownNamespaceNames
docs
or Namespaces
.
The extracted namespace name, or null
if it cannot be determined.
bool HasNamespaceReadmePrefix(IReadOnlyList<string> parts, int namespaceStartIndex)
Determines whether the matched namespace folder appears in one of the supported namespace README locations.
parts
README.md
.namespaceStartIndex
parts
.
true
when the namespace folder lives under a trusted container like docs
or Namespaces
; otherwise, false
.
string NormalizeLookupPath(string path)
Normalizes a documentation path for lookup by trimming slashes and removing fragment anchors.
path
The normalized lookup path.
string? GetFragment(string path)
Extracts the fragment anchor (after the '#') from a documentation path.
path
The fragment string, or null
if no fragment is present.
TimeSpan SnapshotCacheDuration { get; }
Source
Gets the configured absolute lifetime for the shared docs snapshot cache.
Classifies the received request before routing can normalize away alias ownership evidence.
Raw escaped path → one strict decoded validation view → application-relative ownership → safety. The decoded view never becomes a filesystem path. Ownership survives every safety failure.
AppSurfaceDocsAliasRequest? Classify(HttpContext context, IReadOnlyList<string> owners)
Finds an owner in raw, decoded, then framework coordinates and validates the selected path.
context
owners
Sticky owner and accepted label, or null for an unowned request.
bool TryExtractPath(string? target, out string path)
Extracts origin/HTTP absolute-form paths without URI path normalization.
Sticky ownership state; unsafe requests retain the same owner and authorization endpoint.
NamespaceRoot
Name
IsSafe
Harvests explicit Python module, class, function, and method docstrings without executing Python source.
This built-in harvester is deliberately a bounded product spike. It parses only policy-approved .py
files with the Tree-sitter Python grammar, requires a literal top-level __all__
public boundary, and projects plain docstring text rather than a Google, NumPy, or Sphinx documentation dialect. It never imports a module, starts a Python interpreter, evaluates an expression, or derives a general Python visibility policy from an absent boundary.
Task<IReadOnlyList<DocNode>> HarvestAsync(string rootPath, CancellationToken cancellationToken = default)
Scans policy-approved Python files under the repository root and returns generated AppSurface Docs API nodes.
rootPath
cancellationToken
Generated Python module pages plus fragment-addressable symbol nodes.
Task<IReadOnlyList<DocNode>> HarvestAsync(DocHarvestContext context, CancellationToken cancellationToken = default)
Scans Python sources with the repository-scoped path policy captured for the current aggregation pass.
context
cancellationToken
Generated Python module pages plus fragment-addressable symbol nodes.
Represents the authored Markdown code-fence input that AppSurface Docs can render as highlighted or plain code.
Code
null
when an upstream renderer provides no text.Language
null
when omitted.
AppSurfaceDocsCodeBlock
stores only the first whitespace-delimited info-string token in Language
because the renderer treats that token as the language hint. It does not parse full info-string attributes. Language
may be null when the info string is omitted, and Code
may be null when an upstream renderer provides no text, so callers must handle both defensively.
Applies the shared URL-safe grammar for documentation version aliases.
bool TryNormalize(string? value, out string name)
Trims and lowercases a candidate alias, accepting 1–64 ASCII characters with alphanumeric edges and alphanumeric, dot, underscore, or hyphen interior characters.
value
name
true
when the candidate is safe for the alias route segment.
Connects accepted Python module pages with their explicitly declared C# host types.
Both markers are emitted only by built-in static harvesters. The linker intentionally waits until every harvester has succeeded, then requires one accepted Python module and one documented C# owner for each module path. Ambiguous or unmatched declarations disappear from rendered HTML instead of creating a best-effort or potentially broken relationship. The marker values are percent-encoded repository-relative paths so source text never becomes markup.
IReadOnlyList<DocNode> Link(IReadOnlyList<DocNode> nodes, string docsRootPath)
Replaces internal ownership markers with reciprocal, docs-local links.
nodes
docsRootPath
Nodes whose ownership markers have been replaced or removed.
string CreatePythonModuleMarker(string relativePath)
Creates a marker for an accepted Python module source path.
string CreateCSharpOwnerMarker(string relativePath, string anchorId, string displayName)
Creates a marker for a documented C# type that explicitly owns a Python module.
Evaluates host-owned ASP.NET Core policies for AppSurface Docs diagnostics read surfaces.
This adapter is intentionally local to the Docs package. It keeps the diagnostics-read policy independent from the internal Auth.AspNetCore evaluator while preserving ASP.NET Core policy authentication, challenge, forbid, and setup failure semantics for the harvest progress stream.
ValueTask<AppSurfaceAuthResult> AuthorizeAsync(HttpContext httpContext, string policyName, CancellationToken cancellationToken = default)
Evaluates the configured diagnostics read policy against the current request.
httpContext
policyName
cancellationToken
A passive AppSurface auth result representing the policy outcome.
ValueTask<AppSurfaceAuthResult> AuthorizeAsync(HttpContext httpContext, IReadOnlyList<IAuthorizeData> authorizationData, CancellationToken cancellationToken = default)
Evaluates the complete ASP.NET Core authorization metadata applied to a named Docs endpoint group.
httpContext
authorizationData
cancellationToken
A passive AppSurface auth result representing the combined policy outcome.
This preserves default-policy, role, authentication-scheme, and multiple-policy semantics for RazorWire streams, which are not conventional HTTP endpoints and therefore cannot receive ASP.NET Core endpoint authorization automatically.
Defines the repository-relative path policy used by AppSurface Docs harvesters.
Implementations combine configured include or exclude rules with traversal pruning so harvesters can avoid enumerating large excluded directory trees. All paths passed to this contract must be repository-relative and normalized with forward slashes. Absolute paths, parent-directory traversal, and platform-specific separators should be normalized by the caller before evaluation.
AppSurfaceDocsHarvestPathDecision Evaluate(string relativePath, AppSurfaceDocsHarvestSourceKind sourceKind)
Evaluates whether a repository-relative file path should be harvested for the specified source kind.
relativePath
sourceKind
A decision containing the final inclusion result and diagnostic trace entries.
bool ShouldIncludeFilePath(string relativePath, AppSurfaceDocsHarvestSourceKind sourceKind)
Determines whether a repository-relative file path should be included for the specified source kind.
relativePath
sourceKind
true
when the file should be read by the harvester; otherwise false
.
bool ShouldPruneDirectory(string relativeDirectory, AppSurfaceDocsHarvestSourceKind sourceKind)
Determines whether a repository-relative directory can be skipped before its descendants are enumerated.
relativeDirectory
sourceKind
true
when the directory subtree is excluded and can be pruned.
IEnumerable<string> EnumerateCandidateFiles(string rootPath, AppSurfaceDocsHarvestSourceKind sourceKind, string searchPattern, CancellationToken cancellationToken)
Lazily enumerates candidate files below a repository root while applying directory pruning and skipping reparse points.
rootPath
sourceKind
searchPattern
*.md
.cancellationToken
Absolute file paths that match searchPattern
, are not below a pruned directory, and are not file-system reparse points.
File-level include checks are intentionally separate; callers must still pass returned files through ShouldIncludeFilePath
after converting them back to repository-relative paths. Implementations skip reparse-point files and directories before yielding or descending so candidate traversal does not follow symlinks, junctions, or similar filesystem indirection outside the selected repository root.
Applies page-shell heading rules to harvested documentation HTML at render time.
string SuppressLeadingMarkdownH1(string content, bool shellOwnsH1)
Removes the leading rendered Markdown h1
element when the details page shell already renders the page H1.
content
shellOwnsH1
true
when the page shell renders the semantic H1 from Models.DocDetailsViewModel.Title
; false
when the harvested body remains responsible for its own top-level heading.
The original content
when the shell does not own the H1 or when the body does not begin with an h1
; otherwise the body with that first rendered h1
removed.
Only the leading H1 is suppressed. Later H1 elements remain visible because they are authored body structure, not duplicated page chrome.
int GetFirstMeaningfulTokenIndex(string content)
Finds the first non-trivia token in harvested HTML.
content
The index of the first non-trivia token, or -1
when the body is empty or contains only ignorable trivia.
Only leading comments are skipped. Other elements, text, or malformed comments remain authored content and are preserved by the suppressor.
One resolved canonical link, independent of its response mount.
Final-snapshot facts consumed by the pure recommendation policy. Callers resolve authored references and sequence neighbors with the existing route resolver before constructing these facts; only canonical route winners belong here.
A snapshot-owned recommendation. Response projections must detach the page and reason collection.
Diagnostic counts for the candidate union, before source-specific filtering; no runtime tuning surface.
Complete, immutable results and measurements from one policy build.
Selects at most three automatic next reads after an uncapped authored prefix, using only final canonical snapshot metadata. Inverted indexes generate candidates; section, audience and sequence alone never qualify an ordinary page.
Terms are ordinal case-insensitive, trimmed and whitespace-collapsed, with no stemming or punctuation rewriting. Common terms occur on at least five eligible targets and more than one quarter of that target corpus. Derived component/audience values are ignored. Source opt-out does not change target membership or term frequencies. All tie breaks are explicit; input order and current culture have no influence on ranking.
DocRecommendationPolicyResult Build(IReadOnlyList<DocRecommendationPageFacts> pages)
Builds a detached, read-only result for every canonical source. Authored entries retain exact fragment identities and order; automatic entries exclude the owning pages of the source, sequence neighbors and authored entries.
string ReasonText(string primaryReasonCode, bool sharedComponent = false)
Maps stable primary reason codes to the default built-in caption, including future-code fallback.
Serves one or more published AppSurface Docs trees from static export artifacts.
Published trees are usually exported from the stable /docs
surface and then mounted later under the configured route-family root or {RouteRootPath}/v/{version}
. This handler resolves extensionless requests back to the exporter’s .html
files and rewrites stable-root HTML or search-index payloads so the mounted tree stays version-local.
Task<bool> TryHandleAsync(HttpContext httpContext)
Attempts to serve the current request from one of the configured published trees.
httpContext
true
when a published tree handled the request; otherwise false
.
Task HandleOwnedAliasAsync(HttpContext context, AppSurfaceDocsAliasRequest selection)
Consumes an owned alias request terminally after the host's authorization middleware.
context
selection
Task<bool> TryServeMountAsync(HttpContext context, AppSurfaceDocsPublishedTreeMount mount, string requestPath)
Serves exactly the selected mount; a false result never changes that selection.
Task WriteAliasRecoveryAsync(HttpContext context, Microsoft.Extensions.Primitives.StringValues hostContentSecurityPolicy)
Uses one generic, encoded Docs recovery response for all owned GET/HEAD failures.
IEnumerable<string> BuildExportedDocsCandidatePaths(AppSurfaceDocsPublishedTreeMount mount, string requestPath)
Resolves root-export document files without changing the selected verified archive or its bytes.
CDN exports retain the original /docs directory while shared search assets live at the tree root. Flat archives keep their existing precedence. Only verified, inventory-covered HTML candidates qualify for this layout.
IReadOnlyList<string> BuildHtmlDocumentCandidatePaths(string relativeRequestPath)
Builds only the ordinary HTML file candidates that the published route resolver would use for a docs route.
relativeRequestPath
Exact .html
, route.html
, or route/index.html
candidates in serving order.
bool IsAliasNamespaceActive { get; }
Source
Gets whether a catalog actively reserves this instance's alias namespace, including zero mounts.
Describes one published exact-version tree that should be mounted into the active host.
When multiple AppSurfaceDocsPublishedTreeMount
instances overlap, callers should treat the longest MountRootPath
as the winning mount because the request handler resolves mounts from most-specific to least-specific roots before serving content. CanonicalRootPath
controls only canonical-link metadata: normal navigation, search payloads, assets, and frozen-manifest redirects continue to use MountRootPath
.
string MountRootPath { get; }
Source
Gets the request-path root where the tree should appear.
string? AliasName { get; }
Source
Gets the normalized catalog label for dictionary dispatch, or null for legacy mounts.
IFileProvider FileProvider { get; }
Source
Gets the static file provider for the tree contents.
string? ExactTreeRootPath { get; }
Source
Gets the resolved physical root for the exact published tree, when path-guard checks should run.
string CanonicalRootPath { get; }
Source
Gets the app-relative route root canonical metadata should prefer for this mount.
AppSurfaceDocsFrozenRouteManifestCache? FrozenRouteManifest { get; }
Source
Gets the lazy cache for the tree's frozen route manifest, when one should be consulted.
AppSurfaceDocsReleaseArchiveVerificationState ArchiveVerificationState { get; }
Source
Gets the archive-integrity state resolved before this tree was mounted.
AppSurfaceDocsVerifiedReleaseArchive? VerifiedReleaseArchive { get; }
Source
Gets verified archive file metadata, when this mount is backed by a catalog-pinned release manifest.
Rewrites stable-root published-tree content so the same artifact can be served from different mount roots.
Rewrites are mount-aware rather than file-aware. The active AppSurfaceDocsPublishedTreeMount
decides which root wins, and then the rewriter adjusts exported stable-root URLs so they point at that mounted surface. The default stable /docs
surface only needs HTML rewrites when the host adds a non-empty request PathBase
; when the mount root and route root are still /docs
and no PathBase
applies, the exported HTML is already correct and is returned unchanged unless a distinct canonical root, public origin, or generated critical-style nonce applies.
string RewriteHtml(string html, string mountRootPath, string previewRootPath = "/docs/next", string routeRootPath = DocsUrlBuilder.DocsEntryPath, string? requestPathBase = null, string? canonicalRootPath = null, string? publicOrigin = null, bool htmlUsesExportRootUrls = false)
Rewrites stable-root HTML so docs-local links, assets, and client config point at the supplied mount root.
html
mountRootPath
previewRootPath
routeRootPath
requestPathBase
canonicalRootPath
publicOrigin
null
to preserve exported origins.htmlUsesExportRootUrls
The rewritten HTML document.
This method rewrites exported stable-root docs links, assets, and the inline window.__appSurfaceDocsConfig
payload matched by DocsClientConfigRegex
so the document behaves like it was originally emitted for mountRootPath
. As part of that rewrite, the legacy docsVersionsUrl
client field is removed because version archive navigation is rendered server-side. When mountRootPath
and routeRootPath
are both the default /docs
, legacy rewrites only occur if requestPathBase
is non-empty so sub-path-hosted apps still emit /some-base/docs/...
links. Request-scoped CSP nonces are always removed from the generated AppSurface preference bootstrap and critical-theme styles, because published output must remain a deterministic, reusable artifact. The handler recognizes only the package's published bootstrap hash when allowing scripts in a versioned Docs response; all other inline scripts remain blocked. New verified htmlUrlBase: export-root
manifests instead project local HTML attributes and generated redirect refresh URLs from the complete export root beneath the mount, even at stable /docs
. Absolute external URLs and explicitly ignored authoring anchors stay unchanged. This flag must come from the verified frozen snapshot, not request data or live metadata.
string RewriteSearchIndexJson(string json, string mountRootPath, string previewRootPath = "/docs/next", string routeRootPath = DocsUrlBuilder.DocsEntryPath, string? requestPathBase = null)
Rewrites a published search-index payload so mounted document URLs stay inside the active docs surface.
json
mountRootPath
previewRootPath
routeRootPath
requestPathBase
The original payload when it is not a JSON object with a top-level documents
array or when no top-level document path or nested recommendation path requires rewriting; otherwise a payload whose rewritten links stay inside the selected docs mount.
Top-level document paths retain their established mounted-URL rules. For each recommendation row, the original complete URL is validated as a canonical archive recommendation before its path is rebased; the metadata query is discarded and only the validated fragment is retained. Other row identity, display, and reason fields are unchanged. A default stable /docs
mount remains byte-preserving unless a nested query must be removed.
Registers AppSurface Docs' fenced-code renderer with Markdig.
IAppSurfaceDocsCodeHighlighter CreateDefaultHighlighter(ILogger<TextMateSharpAppSurfaceDocsCodeHighlighter> logger)
Creates the default TextMateSharp-backed AppSurface Docs highlighter.
logger
The default AppSurface Docs code highlighter.
Renders Markdown fenced code blocks through AppSurface Docs' highlighter contract.
string? ExtractLanguage(FencedCodeBlock block)
Extracts the first language token from a fenced code block's info string.
block
The first language token, or null
when the fence has no info string.
Resolves authored reader-intent landing curation metadata into browser-facing AppSurface Docs featured-page groups.
The resolver accepts the normalized featured_page_groups
metadata on a landing document, matches each authored destination against harvested docs by source or canonical path, skips destinations that are missing, hidden, blank, or duplicated, and returns only groups that still contain at least one visible page. Logging is intentionally warning-level because curation mistakes degrade first-run docs navigation without breaking application startup.
IReadOnlyList<DocLandingFeaturedPageGroupViewModel> ResolveGroups(DocNode? landingDoc, IReadOnlyList<DocNode> docs)
Resolves grouped featured-page metadata from landingDoc
against the harvested docs corpus.
landingDoc
null
when the caller has no landing page to resolve. docs
A list of resolved featured-page groups ordered by authored group order, then authored position. The method returns an empty list when landingDoc
is null
, when the landing doc has no featured_page_groups
, or when every authored group is filtered out during resolution. Groups with no visible destinations after validation are omitted. Destinations that resolve to docs without a public DocNode.CanonicalPath
are skipped with a warning because collision losers and reserved routes are intentionally not linkable. Duplicate destinations are suppressed across all groups, so a page resolved earlier in authored order will not appear again later in the landing. Browser-facing DocLandingFeaturedPageViewModel.Href
values are rooted at the current live docs surface from DocsUrlBuilder
, not hardcoded to /docs
, and authored canonical input paths are matched against that same configured live docs root before the configured route-family root and legacy stable /docs
prefix fallback are considered.
Lets an optional harvester tell AppSurface Docs whether it should participate in the current source snapshot.
Disabled optional harvesters are omitted from aggregate harvest-health accounting so a deliberately disabled feature cannot convert an otherwise all-failed snapshot into a degraded one. Direct calls to the harvester may still return an empty document set for compatibility.
bool IsEnabled { get; }
Source
Gets a value indicating whether the harvester should run and count toward harvest-health totals.
Describes the include, exclude, or prune outcome for one normalized harvest path.
Included
RelativePath
SourceKind
Code
Trace
MatchedDefaultGroups
Describes one non-fatal AppSurface Docs metadata authoring problem discovered while parsing or normalizing metadata.
Code
FieldPath
featured_page_groups[0].pages
.Problem
Cause
Fix
Carries normalized metadata together with non-fatal diagnostics from a Markdown metadata parse.
Metadata
null
when no usable metadata document was present.Diagnostics
MarkdownDownloadEligibility DownloadEligibility { get; init; }
Source
Gets the strict inline opt-in result for protected Markdown download.
This remains internal parsing state. It lets the Markdown harvester reuse the same front-matter split and YAML validation already required for rendered metadata instead of reparsing the document solely for raw-source eligibility. Sidecar parsing leaves the default MarkdownDownloadEligibility.NotDeclared
value because sidecars cannot grant download access.
Authorizes the AppSurface Docs harvest progress stream with harvest visibility and host-owned stream policy.
ValueTask<bool> CanSubscribeAsync(HttpContext context, string channel)
Determines whether the current request can subscribe to the requested RazorWire channel.
context
channel
true
when channel
passes harvest visibility checks and optional delegated authorization; otherwise false
.
AppSurfaceDocsStreamAuthorization.IsHarvestProgressChannel(string?)
identifies the harvest progress stream so only that channel is tied to AppSurfaceDocsHarvestHealthVisibility.AreRoutesExposed(AppSurfaceDocsOptions, IHostEnvironment)
. The method has no shared mutable state beyond reading constructor dependencies, but the delegated authorizer may perform asynchronous policy checks.
Associates one configured harvester instance with its redacted display name.
ProgressId
HarvesterType
IsBuiltInProgressHarvester
IReadOnlyList<AppSurfaceDocsHarvesterRegistration> Create(IReadOnlyList<string> harvesterTypes)
Creates registrations with unique server-only identities for the supplied harvester type names.
harvesterTypes
Registrations that preserve input order and distinguish repeated type names.
Captures redacted live harvest progress and publishes bounded RazorWire updates for late-subscribing docs pages.
ValueTask<string> BeginRunAsync(IReadOnlyList<string> harvesterTypes)
Begins a new harvest run and publishes the initial waiting snapshot.
harvesterTypes
The generated run identifier used to correlate later progress callbacks.
The snapshot update is protected by the reporter gate and live publication is scheduled after the lock is released. Parser execution never waits for a stream hub response. Because this overload only receives display names, its registrations remain status-only; BeginRunAsync(IReadOnlyList{AppSurfaceDocsHarvesterRegistration})
carries the trusted package-owned parser marker. Passing null
throws ArgumentNullException
.
ValueTask<string> BeginRunAsync(IReadOnlyList<AppSurfaceDocsHarvesterRegistration> harvesterRegistrations)
Begins a new harvest run with stable, server-only identities for each configured harvester instance.
harvesterRegistrations
The generated run identifier used to correlate later progress callbacks.
string? SuppressCompletionVisitForCurrentOrNextRun()
Suppresses the terminal browser visit for the active run, or for the next run if the coordinator has scheduled work before the run has published its identifier.
The run identifier that was suppressed, or null
when suppression was deferred to the next run.
A run can be terminal in the snapshot while its asynchronous completion publish is still in progress. Completed snapshots are therefore still eligible for suppression so a queued rebuild cannot race with a stale terminal visit.
ValueTask RebuildQueuedAsync(string? supersededRunId)
Records that a trusted rebuild is queued behind the active run.
supersededRunId
SuppressCompletionVisitForCurrentOrNextRun
, or null
when the suppression applies to the next unpublished run. A completed task after the updated snapshot has been retained and publication has been scheduled.
When a run identifier is supplied, the queued-state update is ignored if a newer run has already replaced the superseded snapshot. This keeps delayed queued notifications from decorating a fresh rebuild run.
ValueTask HarvesterStartedAsync(string runId, string progressId)
Marks a harvester as running for the correlated harvest run.
runId
progressId
A completed task after the updated snapshot has been retained and publication has been scheduled.
ValueTask HarvesterCompletedAsync(string runId, string progressId, DocHarvesterHealthStatus status, int docCount)
Marks a harvester as terminal and records its document count.
runId
progressId
status
docCount
A completed task after the updated snapshot has been retained and publication has been scheduled.
ValueTask HarvesterDocumentCountUpdatedAsync(string runId, string progressId, int docCount)
Updates the in-progress document count for a harvester.
runId
progressId
docCount
A completed task after the updated snapshot has been retained and publication has been scheduled.
AppSurfaceDocsHarvestProgressSession CreateSession(string runId, string progressId, int testingDelayPerDocumentMilliseconds = 0, CancellationToken cancellationToken = default)
Creates a safe, run-scoped session for one package-owned harvester.
runId
progressId
testingDelayPerDocumentMilliseconds
cancellationToken
The session accepts only closed phase values and numeric deltas. It intentionally has no source-path or display text parameters, so built-in parser telemetry cannot widen the progress redaction boundary.
ValueTask TransitionAsync(string runId, string progressId, AppSurfaceDocsHarvestProgressPhase phase)
Advances one package-owned harvester through its next safe lifecycle phase.
runId
progressId
phase
A completed task after an accepted transition has been retained and publication has been scheduled.
Stale run identifiers and unknown progress identities are ignored. Only the next sequential phase is accepted; waiting and terminal phases are reporter-owned and cannot be set by a harvester session. This preserves the redaction boundary and prevents a delayed parser callback from mutating another harvester or a later run.
void ReportSourceUnit(string runId, string progressId, int documentsFoundDelta)
Records one inspected source unit and the documents it produced for a package-owned harvester.
runId
progressId
documentsFoundDelta
ArgumentOutOfRangeException
documentsFoundDelta
is negative.A zero delta still records the inspected source unit. Stale run identifiers and unknown progress identities are ignored after input validation. Accepted reports are coalesced into ordinary live publication, so callers must not expect a stream update for every source unit.
void ReportOutputOnly(string runId, string progressId, int documentsFoundDelta)
Records output materialized without inspecting a new source unit for a package-owned harvester.
runId
progressId
documentsFoundDelta
ArgumentOutOfRangeException
documentsFoundDelta
is negative.This method deliberately does not increment source-unit telemetry. Stale run identifiers and unknown progress identities are ignored after input validation. Accepted reports are coalesced into ordinary live publication, so callers must not expect a stream update for every output delta.
ValueTask ActivityAsync(string runId, string message)
Adds a bounded activity message to the current run.
runId
message
A completed task after the updated snapshot has been retained and publication has been scheduled.
Messages are kept newest-first and capped to the renderer's activity budget. A stale runId
is ignored, and blank messages throw ArgumentException
.
ValueTask CompleteRunAsync(string runId, DocHarvestHealthSnapshot health)
Completes the correlated run from the final harvest-health snapshot.
runId
health
A completed task after the updated snapshot has been retained and publication has been scheduled.
A failed aggregate health status maps to AppSurfaceDocsHarvestRunState.Failed
; all other terminal statuses map to AppSurfaceDocsHarvestRunState.Completed
. A stale runId
is ignored.
ValueTask FailRunAsync(string runId)
Terminalizes a begun run when aggregation fails after individual harvester execution.
The original aggregation exception remains owned by the caller. This rescue publishes only a generic redacted failure state so an operator is not left with a permanently active observatory if snapshot post-processing fails.
bool IsQueuedRebuildRun(string? supersededRunId)
Determines whether a queued-rebuild status update still belongs to the currently retained running snapshot.
supersededRunId
null
when the queue marker was deferred until the next run published its identifier.
true
when the current snapshot is the run that should carry queued state.
This guard prevents delayed queued-state publishes from decorating a fresh rebuild after the original run has already completed. Callers must hold _gate
while invoking this helper so the snapshot and deferred marker are compared atomically.
AppSurfaceDocsHarvestProgressSnapshot CurrentSnapshot { get; }
Source
Gets the latest redacted harvest progress snapshot.
Access is synchronized through the reporter gate so callers receive a consistent snapshot instance. The returned record is immutable by convention through init-only properties.
int CompletionDelay { get; }
Source
Gets the client-side completion navigation delay in milliseconds.
string StreamChannelName { get; }
Source
Gets the RazorWire stream channel owned by this Docs runtime.
TimeProvider TimeProvider { get; }
Source
Gets the time source shared with run-scoped test pacing and rate measurement.
int SuppressedCompletionVisitCount { get; }
Source
Gets the number of run identifiers whose terminal completion visit is currently suppressed.
This test seam keeps suppression cleanup verifiable without exposing the mutable set or using reflection. Production callers should use SuppressCompletionVisitForCurrentOrNextRun
instead of observing this count.
Renders encoded harvest progress HTML fragments for the AppSurface Docs observatory.
The renderer accepts already-redacted progress snapshots and emits bounded markup for full pages and Turbo stream updates. It HTML-encodes text and attribute values, truncates activity to eight entries and diagnostics to four, and treats AppSurfaceDocsHarvestRunState.Completed
and AppSurfaceDocsHarvestRunState.Failed
as terminal states. The renderer intentionally does not accept request-derived return URLs; Razor views should emit those values through normal attribute or link rendering after validating that they are app-relative.
string Render(AppSurfaceDocsHarvestProgressSnapshot snapshot, int completionDelayMilliseconds)
Renders the observatory fragment for a harvest progress snapshot.
snapshot
completionDelayMilliseconds
An encoded HTML fragment for the observatory surface.
When the snapshot is completed, the fragment includes the completion marker and delay used by the client script to refresh after the configured delay. Failed runs render diagnostics but do not auto-refresh. The containing Razor view owns request-derived return links so they are emitted by Razor's encoder rather than this raw fragment.
IHtmlContent RenderHtml(AppSurfaceDocsHarvestProgressSnapshot snapshot, int completionDelayMilliseconds)
Renders the observatory fragment as HTML-safe content for Razor views.
snapshot
completionDelayMilliseconds
HTML-safe observatory markup with all dynamic text encoded.
Use this method from package-owned Razor views instead of Html.Raw
. Request-derived navigation values belong in the surrounding view model and should be emitted by Razor attributes or anchors after validation.
string RenderTurboStream(AppSurfaceDocsHarvestProgressSnapshot snapshot, int completionDelayMilliseconds)
Renders a Turbo stream update for the harvest observatory target.
snapshot
completionDelayMilliseconds
A Turbo stream update that replaces the observatory content.
The outer page owns navigation timing and request-derived return links; the emitted fragment only carries completion state for client-side refresh scheduling.
Renders configured AppSurface Docs wordmarks for package-owned Razor views.
This helper keeps the docs chrome's encoded wordmark markup in one place so layout and landing views share the same highlight splitting, CSS variable placement, and plain-text fallback. It only consumes resolved identity values; the options post-configuration and validator remain the source of truth for trimming, matching, and color safety.
IHtmlContent Render(AppSurfaceDocsResolvedIdentity identity, string cssClass, string elementName = "span")
Renders the resolved identity display name with the optional configured wordmark highlight.
identity
cssClass
elementName
span
and h1
.HTML-safe wordmark markup with all display text encoded.
Projects authored Markdown summaries into the small, safe display contract used by docs search results.
The projector deliberately uses Markdig's base parser rather than the Docs rendering pipeline. Search-result previews need semantic inline formatting, not HTML, extensions, attributes, links, or renderer behavior. Its output is bounded to protect browser consumers even when a summary is author-authored or sourced from an external index.
IReadOnlyList<DocsSearchSummaryPresentationNode>? Project(string? summary)
Projects one raw Markdown summary, returning null
when it has no reader-facing content.
summary
A bounded display tree, or null
when no usable text remains.
bool TryClassifySuppressedHtmlTag(string tag, out bool isClosing, out bool isSelfClosing)
Classifies the raw HTML tags that suppress their inline contents from a search summary.
tag
isClosing
tag
closes a suppressed element.isSelfClosing
tag
is self-closing.
true
when the tag is a script or style element; otherwise, false
.
Accumulates the bounded presentation tree while enforcing node and scalar budgets.
Internal visibility permits direct verification of defensive budget guards that valid Markdown cannot reach.
void BeginBlock()
Records a boundary between reader-visible Markdown blocks.
MutableNode? AddContainer(List<MutableNode> target, string kind, int depth)
Adds a formatted container when the depth and node budgets allow it.
target
kind
depth
The added node, or null
after budget truncation.
void AppendText(List<MutableNode> target, string kind, string? value, int depth)
Normalizes and appends a bounded text or code leaf.
target
kind
value
depth
void RemoveNode()
Reclaims the node count after a newly created empty container is discarded.
IReadOnlyList<DocsSearchSummaryPresentationNode>? Build()
Materializes a safe immutable presentation tree.
The immutable nodes, or null
when no reader-visible text remains.
List<MutableNode> Root { get; }
Source
Gets the mutable top-level nodes collected for the current projection.
bool IsTruncated { get; set; }
Source
Gets whether the builder has emitted its terminal truncation marker.
Holds one mutable presentation node until projection construction completes.
DocsSearchSummaryPresentationNode? ToImmutable()
Converts this node and its valid descendants into the public immutable contract.
The immutable node, or null
when no visible content remains.
string Kind { get; }
Source
Gets the safe presentation-node kind.
StringBuilder Text { get; }
Source
Gets the mutable text leaf content.
List<MutableNode> Children { get; }
Source
Gets the child nodes for formatted containers.
Normalizes and validates browser paths used by AppSurface Docs identity options.
Keep this helper as the single policy point for brand asset and home-link paths. The options post-configurator, validator, and resolved identity service all depend on the same rules so path behavior cannot drift between appsettings, environment variables, startup validation, and Razor rendering.
string? NormalizeTextOrNull(string? value)
Trims a text option value and treats blank text as omitted.
value
The trimmed text, or null
when the value is null, empty, or whitespace.
string NormalizeDisplayName(string? displayName)
Resolves the visible AppSurface Docs display name.
displayName
The trimmed display name, or AppSurfaceDocsIdentityOptions.DefaultDisplayName
when blank.
string? NormalizeBrowserPathOrNull(string? value)
Normalizes a browser path when it is valid and preserves invalid non-blank text for later validation errors.
value
A normalized path when valid, the trimmed original value when invalid, or null
when blank.
string? NormalizeCssHexColorOrNull(string? value)
Normalizes a CSS hex color and preserves invalid non-blank text for later validation errors.
value
A lower-invariant CSS hex color when valid, the trimmed original value when invalid, or null when blank.
bool TryNormalizeCssHexColor(string? value, out string? normalizedColor, out string error)
Validates and normalizes a CSS hex color suitable for the package-owned wordmark style variable.
value
normalizedColor
error
True when the value is blank, a three-digit hex color, or a six-digit hex color; otherwise false.
bool TryNormalizeBrowserPath(string? value, out string? normalizedPath, out string error)
Validates and normalizes an app-root or application-relative browser path.
value
normalizedPath
null
.error
true
when the value is blank, starts with /
, or starts with ~/
and does not contain remote URL, data URL, query string, fragment, backslash, or traversal segments; otherwise false
.
Captures the configured harvest path policy and repository VCS ignore policy used for one harvest snapshot.
The snapshot keeps VCS ignore parsing stable for a single aggregation pass and exposes only normalized, repository-relative decisions to harvesters through IHarvestPathPolicy
. The configured policy is evaluated first, and VCS ignore decisions are applied as an additional exclusion layer with allow-glob restoration for intentionally public ignored content.
IEnumerable<string> EnumerateCandidateFiles(string rootPath, AppSurfaceDocsHarvestSourceKind sourceKind, string searchPattern, CancellationToken cancellationToken)
Traversal is lazy and depth-first using the shared AppSurface Docs harvest filesystem helper. File paths are yielded as absolute paths, directory paths are normalized to forward-slash repository-relative values before pruning, and directory reparse points are skipped to avoid following symlinks or junctions outside the repository. File reparse points are skipped for the same reason, so symlinked files cannot point harvesters at content outside the repository boundary. Cancellation is checked before each directory expansion, so callers can stop large repository walks without waiting for every descendant to be listed. The method throws ArgumentNullException
for a null
rootPath
or searchPattern
; file-system enumeration exceptions are allowed to flow to the harvester so the aggregation layer can report the failure consistently.
AppSurfaceDocsHarvestVcsIgnoreDiagnostics GetVcsIgnoreDiagnostics()
Gets repository VCS ignore loading diagnostics for this harvest snapshot.
VCS ignore status, loaded ignore files, and warning information.
IReadOnlyList<DocHarvestDiagnostic> CreateVcsIgnoreHealthDiagnostics()
Creates health diagnostics that summarize VCS ignore behavior for the snapshot.
Diagnostics safe for harvest health reporting. Sample paths are redacted before client exposure.
Creates per-harvest path policy snapshots for a repository root.
A new snapshot should be created for each aggregation pass so changes to repository ignore files are observed at the beginning of the next harvest while remaining stable for all harvesters in the current pass.
AppSurfaceDocsHarvestPathPolicySnapshot Create(string repositoryRoot)
Creates a path policy snapshot for the supplied repository root.
repositoryRoot
A snapshot combining configured path rules with repository VCS ignore rules.
Carries repository-scoped harvest dependencies shared by built-in harvesters during one aggregation pass.
RepositoryRoot
PathPolicy
Progress
The context keeps harvesters on a single policy instance for consistent VCS ignore decisions. Consumers should treat PathPolicy
as the authority for traversal and file inclusion, and should not cache the context beyond the aggregation pass that created it.
Resolves authored, source, and canonical AppSurface Docs paths against a harvested documentation corpus.
AppSurface Docs accepts paths from several authoring surfaces: browser routes, source-relative Markdown metadata, generated canonical paths, and route-prefixed links. This resolver is the shared source of truth for trimming route separators, ignoring lookup fragments when selecting candidate buckets, preserving exact fragment matches when available, and ranking fallback candidates when a fragment-specific page is not present.
DocPathResolver Create(IEnumerable<DocNode> docs)
Builds a resolver for a docs snapshot.
docs
A resolver that can match source paths, canonical route paths, and route-relative variants.
DocNode? Resolve(string path)
Resolves a path exactly as authored, using AppSurface Docs source and canonical matching rules.
path
The best matching doc node, or null
when no harvested doc matches.
DocNode? Resolve(string path, params string[] routeRootPaths)
Resolves a path by preserving authored source-relative matches before stripping known docs route roots from browser-facing inputs.
path
routeRootPaths
/docs
root.
The best matching doc node, or null
when neither route-relative variants nor the original path match.
string NormalizeLookupPath(string path)
Normalizes a documentation path for lookup by trimming route separators and removing fragment anchors.
path
The normalized lookup path.
string NormalizeCanonicalPath(string path)
Normalizes a documentation path for canonical comparison by trimming route separators while preserving fragments.
path
The normalized canonical path.
string? GetFragment(string path)
Extracts a fragment from a documentation path after canonical normalization.
path
The fragment without the leading #
, or null
when no non-empty fragment exists.
Normalizes harvested non-Markdown source paths into legacy browser-facing routes used by AppSurface Docs.
A harvested source path is the repository-relative or generated path assigned to a DocNode
before AppSurface Docs publishes it. This helper is intentionally narrow: it exists for generated or imported non-Markdown sources such as XML API reference pages, generated JSON or YAML API specs, and imported HTML fragments that still use the historical .html
route shape. Markdown documents should use DocRouteIdentityCatalog
instead, because that catalog owns clean public routes, redirect aliases, collisions, and reserved-route diagnostics.
string BuildCanonicalPath(string sourcePath)
Constructs a legacy browser-facing path for a harvested non-Markdown documentation source path.
sourcePath
The legacy docs route path, including the .html
suffix used by generated API docs and any original fragment identifier. Markdown public routes are owned by DocRouteIdentityCatalog
.
Use this method only when a source must keep the generated-docs compatibility contract where Namespaces/Foo.Bar
becomes Namespaces/Foo.Bar.html
. It trims leading and trailing separators, preserves fragments, normalizes backslashes to slashes, and appends .html
unless the final file name already has that suffix. The word "canonical" in the method name refers to this legacy generated-doc route canonicalization; it does not mean the clean Markdown route contract. For authored Markdown pages, callers should query DocRouteIdentityCatalog
so explicit canonical_slug
, redirect aliases, public-route collisions, and reserved-route checks all remain centralized.
Describes how the current host resolved its published-version catalog state.
Numeric values are explicit and stable because callers may serialize or persist catalog-resolution state across process boundaries.
Describes the archive-integrity state resolved for a published AppSurface Docs version.
Numeric values are explicit and stable because catalog diagnostics, command output, and downstream consumers may serialize or persist these states outside the current process.
Describes the rule outcome that caused a harvest path decision or trace entry.
Describes how the built-in JavaScript harvester may treat a file-system candidate before reading or traversal.
Identifies a package-owned rich-authoring directive family.
Stable rejection categories for published search-index document path validation.
Use enum members for local control flow and PublishedSearchIndexDocumentPathPolicy.ToDiagnosticCode(PublishedSearchIndexPathRejectionReason)
for telemetry, log fields, and persisted diagnostics. The policy returns the first matching category in its ordered checks, so a value that is both off-root and reserved reports the earlier root or syntax failure.
Result of a trusted operator request to rebuild the live AppSurface Docs harvest.
The default enum value, 0
, is not a valid rebuild request result. Callers that bind, deserialize, or display unknown values should treat them as "no request result." While a harvest is active, rebuild requests are coalesced so at most one superseding rebuild is queued behind the active run. The numeric member values are part of the public compatibility contract and must not be reordered or renumbered.
Describes whether an inline Markdown source declaration grants protected download eligibility.
Identifies why an AppSurface Docs route alias exists.
Enumerates package-defined default exclusion groups used by harvest path policy evaluation.
Member names are stable internal configuration IDs consumed by DisabledGroups
and AllowGlobs
. Do not rename existing members without a migration plan; append new members for new groups.
Identifies the content source type being evaluated by the harvest path policy.