Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 10 additions & 16 deletions tools/BootstrapBlazor.LLMsDocsGenerator/ArgumentsHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,42 +12,36 @@ internal static class ArgumentsHelper
public static ParseResult Parse(string[] args)
{
const string defaultFolder = ".";
var rootFolderOption = new Option<string?>("--root")
{
Description = "Set the Server project folder (core-only can instead run from the core project)"
};
var outputFolderOption = new Option<string>("--output")
{
Description = "Set the output folder (core-only writes directly; default writes to wwwroot/llms)",
Description = "Set the output folder (defaults to the current directory)",
DefaultValueFactory = _ => defaultFolder
};
var coreOnlyOption = new Option<bool>("--core-only")
var projectOption = new Option<string?>("--project")
{
Description = "Generate only core components and services for BootstrapBlazor packaging, without extension sources"
Description = "Project file or directory to analyze (defaults to the current directory)"
};

var rootCommand = new RootCommand("BootstrapBlazor LLMs Documentation Generator")
{
rootFolderOption,
outputFolderOption,
coreOnlyOption
projectOption
};

rootCommand.SetAction(async result =>
{
var rootFolder = result.GetValue(rootFolderOption);
if (rootFolder != null && string.IsNullOrWhiteSpace(rootFolder))
{
throw new ArgumentException("Project root folder must not be empty.");
}

var outputFolder = result.GetValue(outputFolderOption);
if (string.IsNullOrEmpty(outputFolder))
{
throw new ArgumentException("Output folder must not be empty.");
}

await DocsGenerator.GenerateAllAsync(rootFolder, outputFolder, result.GetValue(coreOnlyOption));
var project = result.GetValue(projectOption);
if (project != null && string.IsNullOrWhiteSpace(project))
{
throw new ArgumentException("--project requires a nonempty path.");
}
await DocsGenerator.GenerateAllAsync(outputFolder, project);
});

return rootCommand.Parse(args);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Version>11.0.2</Version>
<Version>11.0.3</Version>
<OutputType>Exe</OutputType>
<SatelliteResourceLanguages>false</SatelliteResourceLanguages>
</PropertyGroup>
Expand All @@ -10,6 +10,8 @@
<Title>BootstrapBlazor LLMs docs Generator</Title>
<Description>Generates LLM-friendly API documentation for BootstrapBlazor components from source code.</Description>
<PackageId>BootstrapBlazor.LLMsDocsGenerator</PackageId>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackAsTool>true</PackAsTool>
<ToolCommandName>llms-docs</ToolCommandName>
</PropertyGroup>
Expand Down
63 changes: 53 additions & 10 deletions tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ public partial class ComponentAnalyzer
private readonly string? _samplesPath;
private readonly string? _extensionsSourcePath;
private readonly IReadOnlyDictionary<string, string>? _extensionProjects;
private readonly bool _singleProject;
private readonly string? _extensionRepository;

private CSharpCompilation? _compilation;
private readonly Dictionary<string, SyntaxTree> _treeByPath = new(StringComparer.OrdinalIgnoreCase);
Expand All @@ -52,10 +54,13 @@ public ComponentAnalyzer(string sourcePath, string? extensionsSourcePath = null,
}

internal ComponentAnalyzer(string sourcePath, string? extensionsSourcePath,
IReadOnlyDictionary<string, string>? extensionProjects, bool includeSamples)
IReadOnlyDictionary<string, string>? extensionProjects, bool includeSamples, bool singleProject = false)
{
_sourcePath = sourcePath;
_componentsPath = Path.Combine(sourcePath, "Components");
_singleProject = singleProject;
_componentsPath = singleProject ? sourcePath : Path.Combine(sourcePath, "Components");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Non-components appear as components

When the project contains a matching entry file whose class is not a component, AnalyzeAllComponentsAsync passes matching files to AnalyzeEntryFile without checking IsComponentType, and the _singleProject condition retains results even when they have no component parameters. The index and generated documents therefore list helper or base classes as components.

Filter analyzed entry-file types with IsComponentType before adding them to the component list.

Also at tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs:102.

Prompt for AI agents
In `tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs` at line 61:

**Non-components appear as components**

When the project contains a matching entry file whose class is not a component, `AnalyzeAllComponentsAsync` passes matching files to `AnalyzeEntryFile` without checking `IsComponentType`, and the `_singleProject` condition retains results even when they have no component parameters. The index and generated documents therefore list helper or base classes as components.

Filter analyzed entry-file types with `IsComponentType` before adding them to the component list.

Also at `tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs:102`.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Nested project APIs enter the docs

When the selected project directory contains a nested test or auxiliary project with discoverable types, the project-wide recursive scans include nested-project sources, and AnalyzeProjectServicesAsync can also include their public services. The generated documentation therefore contains APIs that do not belong to the selected project.

Exclude nested project directories and their source files from compilation and analysis.

Prompt for AI agents
In `tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs` at line 61:

**Nested project APIs enter the docs**

When the selected project directory contains a nested test or auxiliary project with discoverable types, the project-wide recursive scans include nested-project sources, and `AnalyzeProjectServicesAsync` can also include their public services. The generated documentation therefore contains APIs that do not belong to the selected project.

Exclude nested project directories and their source files from compilation and analysis.

_extensionRepository = singleProject
? FindExtensionRepository(sourcePath) : null;
_samplesPath = includeSamples
? Path.Combine(Path.GetDirectoryName(sourcePath)!, "BootstrapBlazor.Server", "Components", "Samples")
: null;
Expand Down Expand Up @@ -86,14 +91,15 @@ public async Task<List<ComponentInfo>> AnalyzeAllComponentsAsync()
.Concat(Directory.GetFiles(_componentsPath, "*Base.cs", SearchOption.AllDirectories))
.Concat(Directory.GetFiles(_componentsPath, "*.razor", SearchOption.AllDirectories)
.Where(file => !File.Exists(file + ".cs") && _treeByPath.ContainsKey(Path.GetFullPath(file))))
.Where(IsCompilableSource)
.Distinct(StringComparer.OrdinalIgnoreCase);

var seenTypes = new HashSet<string>(StringComparer.Ordinal);

foreach (var file in entryFiles)
{
var component = AnalyzeEntryFile(file);
if (component != null && component.Parameters.Count > 0 && seenTypes.Add(component.FullName))
if (component != null && (_singleProject || component.Parameters.Count > 0) && seenTypes.Add(component.FullName))
{
components.Add(component);
}
Expand All @@ -119,7 +125,7 @@ public async Task<List<ComponentInfo>> AnalyzeAllComponentsAsync()
}

var component = BuildComponentInfo(symbol, declaration, declaration.SyntaxTree.FilePath);
if (component.Parameters.Count > 0 && seenTypes.Add(component.FullName))
if ((_singleProject || component.Parameters.Count > 0) && seenTypes.Add(component.FullName))
{
components.Add(component);
}
Expand Down Expand Up @@ -226,7 +232,7 @@ public async Task<List<ComponentInfo>> AnalyzeServicesAsync(IEnumerable<string>
return services;
}

internal async Task<List<ComponentInfo>> AnalyzeCoreServicesAsync(IEnumerable<ComponentInfo> components)
internal async Task<List<ComponentInfo>> AnalyzeProjectServicesAsync(IEnumerable<ComponentInfo> components)
{
await EnsureCompilationAsync();

Expand All @@ -240,7 +246,7 @@ internal async Task<List<ComponentInfo>> AnalyzeCoreServicesAsync(IEnumerable<Co
var path = Path.GetFullPath(tree.FilePath);
var inServices = path.StartsWith(servicePath, StringComparison.OrdinalIgnoreCase);
var inComponents = path.StartsWith(componentPath, StringComparison.OrdinalIgnoreCase);
if (!inServices && !inComponents)
if (!_singleProject && !inServices && !inComponents)
{
continue;
}
Expand All @@ -260,7 +266,9 @@ internal async Task<List<ComponentInfo>> AnalyzeCoreServicesAsync(IEnumerable<Co

var isService = symbol.TypeKind == TypeKind.Interface &&
(inServices || symbol.Name.EndsWith("Service", StringComparison.Ordinal) || symbol.Name.EndsWith("Provider", StringComparison.Ordinal))
|| symbol.TypeKind == TypeKind.Class && symbol.Name.EndsWith("Service", StringComparison.Ordinal);
|| symbol.TypeKind == TypeKind.Class &&
(symbol.Name.EndsWith("Service", StringComparison.Ordinal) ||
_singleProject && symbol.Name.EndsWith("Provider", StringComparison.Ordinal));
if (!isService)
{
continue;
Expand All @@ -273,15 +281,25 @@ internal async Task<List<ComponentInfo>> AnalyzeCoreServicesAsync(IEnumerable<Co

if (symbols.TryGetValue(symbol.Name, out var existing) && !SymbolEqualityComparer.Default.Equals(existing, symbol))
{
throw new InvalidDataException($"Core service names collide: {existing.ToDisplayString()} and {symbol.ToDisplayString()}");
throw new InvalidDataException($"Service names collide: {existing.ToDisplayString()} and {symbol.ToDisplayString()}");
}

symbols[symbol.Name] = symbol;
}
}

return symbols.Values.OrderBy(symbol => symbol.Name, StringComparer.Ordinal)
.Select(symbol => BuildServiceInfo(symbol, includeTypeParameters: true)).ToList();
.Select(symbol =>
{
var info = BuildServiceInfo(symbol, includeTypeParameters: true);
if (_singleProject)
{
info.IsExtension = _extensionRepository != null;
info.SuppressSourceLink = _extensionRepository == null;
info.Registrations = ResolveRegistrations(symbol, null);
}
return info;
}).ToList();
}

private ComponentInfo BuildServiceInfo(INamedTypeSymbol symbol, bool includeTypeParameters = false)
Expand Down Expand Up @@ -574,6 +592,11 @@ private static List<UsingDirectiveSyntax> ReadProjectUsings(string projectDirect
private async Task<string?> BuildInheritsShimAsync(string razorFile)
{
var content = await File.ReadAllTextAsync(razorFile);
if (_singleProject && (Path.GetFileName(razorFile).StartsWith('_') ||
content.Split('\n').Any(line => line.TrimStart().StartsWith("@page ", StringComparison.Ordinal))))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Routable pages enter component docs

When a Razor page uses a tab between @page and its route, a valid Razor @page directive separated from its route by a tab does not match the literal "@page " check, so BuildInheritsShimAsync synthesizes a component for that page and the generator publishes it as a component.

Recognize Razor directive whitespace with a whitespace-aware check, or parse the directive using Razor syntax.

Prompt for AI agents
In `tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs` at line 596:

**Routable pages enter component docs**

When a Razor page uses a tab between `@page` and its route, a valid Razor `@page` directive separated from its route by a tab does not match the literal `"@page "` check, so `BuildInheritsShimAsync` synthesizes a component for that page and the generator publishes it as a component.

Recognize Razor directive whitespace with a whitespace-aware check, or parse the directive using Razor syntax.

{
return null;
Comment on lines +595 to +598

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Routed pages enter component index

When a single-project input contains a routable .razor page with a .razor.cs code-behind file, the page's .razor.cs file is still selected as an entry file and AnalyzeEntryFile adds its type without checking whether the paired Razor file has @page. Routable pages with code-behind therefore appear as components in the generated index despite the new page exclusion.

Apply the @page exclusion to the paired Razor/code-behind entry before adding the type to the component list.

Prompt for AI agents
In `tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs` at lines 595-598:

**Routed pages enter component index**

When a single-project input contains a routable `.razor` page with a `.razor.cs` code-behind file, the page's `.razor.cs` file is still selected as an entry file and `AnalyzeEntryFile` adds its type without checking whether the paired Razor file has `@page`. Routable pages with code-behind therefore appear as components in the generated index despite the new page exclusion.

Apply the `@page` exclusion to the paired Razor/code-behind entry before adding the type to the component list.

}

string? baseType = null;
string? ns = null;
Expand Down Expand Up @@ -601,10 +624,11 @@ private static List<UsingDirectiveSyntax> ReadProjectUsings(string projectDirect
}
}

if (string.IsNullOrEmpty(baseType))
if (string.IsNullOrEmpty(baseType) && !_singleProject)
{
return null;
}
baseType ??= "ComponentBase";

var className = Path.GetFileNameWithoutExtension(razorFile);
ns ??= GetNamespaceForRazor(razorFile) ?? "BootstrapBlazor.Components";
Expand Down Expand Up @@ -695,6 +719,8 @@ private ComponentInfo BuildComponentInfo(INamedTypeSymbol symbol, ClassDeclarati
TypeParameters = symbol.TypeParameters.Select(t => t.Name).ToList(),
BaseClass = GetBaseClassName(symbol),
SourcePath = GetRelativePath(filePath),
IsExtension = _singleProject && _extensionRepository != null,
SuppressSourceLink = _singleProject && _extensionRepository == null,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Core source links are omitted

When generation targets the BootstrapBlazor core project, SuppressSourceLink is set whenever _extensionRepository is null, including for the core repository. The Markdown builder therefore omits source links from generated pages despite the available core GitHub raw URL.

Set SuppressSourceLink based on whether a source link is actually available, rather than whether an extensions repository was detected.

Also at tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs:298.

Prompt for AI agents
In `tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs` at line 723:

**Core source links are omitted**

When generation targets the BootstrapBlazor core project, `SuppressSourceLink` is set whenever `_extensionRepository` is null, including for the core repository. The Markdown builder therefore omits source links from generated pages despite the available core GitHub raw URL.

Set `SuppressSourceLink` based on whether a source link is actually available, rather than whether an extensions repository was detected.

Also at `tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs:298`.

LastModified = File.GetLastWriteTimeUtc(filePath),
SamplePath = FindSamplePath(symbol.Name),
Parameters = CollectParameters(symbol),
Expand Down Expand Up @@ -1042,6 +1068,10 @@ private static (bool IsObsolete, string? Message) GetObsoleteInfo(MemberDeclarat
private string GetRelativePath(string fullPath)
{
var full = Path.GetFullPath(fullPath);
if (_singleProject)
{
return Path.GetRelativePath(_extensionRepository ?? _sourcePath, full).Replace('\\', '/');
}

// Extension sources live in a separate repository; make the path relative to
// that repo root (the parent of its src folder).
Expand All @@ -1053,6 +1083,7 @@ private string GetRelativePath(string fullPath)
var extRoot = Path.GetDirectoryName(extSrc)!;
return Path.GetRelativePath(extRoot, full).Replace('\\', '/');
}

}

var sourceRoot = Path.GetFullPath(_sourcePath);
Expand All @@ -1065,6 +1096,18 @@ private string GetRelativePath(string fullPath)
return Path.GetRelativePath(basePath, full).Replace('\\', '/');
}

private static string? FindExtensionRepository(string sourcePath)
{
for (var directory = new DirectoryInfo(Path.GetFullPath(sourcePath)); directory != null; directory = directory.Parent)
{
if (File.Exists(Path.Combine(directory.FullName, "BootstrapBlazor.Extensions.slnx")))
{
return directory.FullName;
}
}
return null;
}

private string? FindSamplePath(string componentName)
{
if (_samplesPath == null || !Directory.Exists(_samplesPath))
Expand Down
2 changes: 2 additions & 0 deletions tools/BootstrapBlazor.LLMsDocsGenerator/ComponentInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ public class ComponentInfo
/// </summary>
public bool IsExtension { get; set; }

public bool SuppressSourceLink { get; set; }

/// <summary>
/// Dependency-injection registration for an extension service, resolved from the
/// <c>AddXxx(this IServiceCollection)</c> extension method that registers this type.
Expand Down
Loading
Loading