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
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Version>11.0.3</Version>
<Version>11.0.4</Version>
<OutputType>Exe</OutputType>
<SatelliteResourceLanguages>false</SatelliteResourceLanguages>
</PropertyGroup>
Expand Down
42 changes: 32 additions & 10 deletions tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ internal async Task<List<ComponentInfo>> AnalyzeProjectServicesAsync(IEnumerable
foreach (var declaration in tree.GetRoot().DescendantNodes().OfType<TypeDeclarationSyntax>())
{
if (model.GetDeclaredSymbol(declaration) is not INamedTypeSymbol symbol ||
symbol.DeclaredAccessibility != Accessibility.Public || symbol.ContainingType != null || symbol.IsStatic ||
symbol.DeclaredAccessibility != Accessibility.Public || symbol.ContainingType != 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 · Obsolete APIs appear supported

When an obsolete type or registration method uses a using alias for System.ObsoleteAttribute, ComponentAnalyzer compares attribute syntax names in both type and method checks, so it includes the obsolete declaration in the generated index and documentation as supported.

Resolve each attribute to its symbol and exclude declarations whose attribute symbol is System.ObsoleteAttribute.

Also at tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs:798-806.

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

**Obsolete APIs appear supported**

When an obsolete type or registration method uses a using alias for System.ObsoleteAttribute, `ComponentAnalyzer` compares attribute syntax names in both type and method checks, so it includes the obsolete declaration in the generated index and documentation as supported.

Resolve each attribute to its symbol and exclude declarations whose attribute symbol is `System.ObsoleteAttribute`.

Also at `tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs:798-806`.

symbol.DeclaringSyntaxReferences.Select(reference => reference.GetSyntax())
.OfType<TypeDeclarationSyntax>().SelectMany(type => type.AttributeLists)
.SelectMany(list => list.Attributes).Any(attribute =>
Expand All @@ -264,12 +264,14 @@ internal async Task<List<ComponentInfo>> AnalyzeProjectServicesAsync(IEnumerable
continue;
}

var isService = symbol.TypeKind == TypeKind.Interface &&
var isService = !symbol.IsStatic && (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) ||
_singleProject && symbol.Name.EndsWith("Provider", StringComparison.Ordinal));
if (!isService)
_singleProject && symbol.Name.EndsWith("Provider", StringComparison.Ordinal)));
var isRegistrationExtension = _singleProject && symbol.IsStatic &&
symbol.GetMembers().OfType<IMethodSymbol>().Any(IsServiceRegistrationMethod);
if (!isService && !isRegistrationExtension)
{
continue;
}
Expand All @@ -291,18 +293,21 @@ internal async Task<List<ComponentInfo>> AnalyzeProjectServicesAsync(IEnumerable
return symbols.Values.OrderBy(symbol => symbol.Name, StringComparer.Ordinal)
.Select(symbol =>
{
var info = BuildServiceInfo(symbol, includeTypeParameters: true);
var info = BuildServiceInfo(symbol, includeTypeParameters: true, serviceRegistrationsOnly: symbol.IsStatic);
if (_singleProject)
{
info.IsExtension = _extensionRepository != null;
info.SuppressSourceLink = _extensionRepository == null;
info.Registrations = ResolveRegistrations(symbol, null);
if (!symbol.IsStatic)
{
info.Registrations = ResolveRegistrations(symbol, null);
}
}
return info;
}).ToList();
}

private ComponentInfo BuildServiceInfo(INamedTypeSymbol symbol, bool includeTypeParameters = false)
private ComponentInfo BuildServiceInfo(INamedTypeSymbol symbol, bool includeTypeParameters = false, bool serviceRegistrationsOnly = false)
{
var syntax = symbol.DeclaringSyntaxReferences.First().GetSyntax();
return new ComponentInfo
Expand All @@ -312,7 +317,8 @@ private ComponentInfo BuildServiceInfo(INamedTypeSymbol symbol, bool includeType
Summary = ExtractXmlSummary(syntax),
TypeParameters = includeTypeParameters ? symbol.TypeParameters.Select(type => type.Name).ToList() : new(),
SourcePath = GetRelativePath(syntax.SyntaxTree.FilePath),
PublicMethods = CollectMethods(symbol)
PublicMethods = CollectMethods(symbol, serviceRegistrationsOnly),
IsServiceRegistrationExtension = serviceRegistrationsOnly
};
}

Expand Down Expand Up @@ -789,11 +795,22 @@ private List<ParameterInfo> CollectParameters(INamedTypeSymbol type)
return parameters.OrderBy(p => p.Name).ToList();
}

private static bool IsServiceRegistrationMethod(IMethodSymbol method)
{
return method.DeclaredAccessibility == Accessibility.Public && method.IsExtensionMethod &&
(method.Name.StartsWith("Add", StringComparison.Ordinal) || method.Name.StartsWith("TryAdd", StringComparison.Ordinal)) &&
method.Parameters[0].Type.Name == "IServiceCollection" &&
!method.DeclaringSyntaxReferences.Select(reference => reference.GetSyntax())
.OfType<MethodDeclarationSyntax>().SelectMany(declaration => declaration.AttributeLists)
.SelectMany(list => list.Attributes).Any(attribute =>
attribute.Name.ToString().Split('.').Last() is "Obsolete" or "ObsoleteAttribute");
}

/// <summary>
/// Collect public methods declared on the component itself (partials merged),
/// excluding overrides, constructors, accessors and operators.
/// </summary>
private List<MethodInfo> CollectMethods(INamedTypeSymbol type)
private List<MethodInfo> CollectMethods(INamedTypeSymbol type, bool serviceRegistrationsOnly = false)
{
var methods = new List<MethodInfo>();

Expand All @@ -802,7 +819,8 @@ private List<MethodInfo> CollectMethods(INamedTypeSymbol type)
if (method.DeclaredAccessibility != Accessibility.Public ||
method.IsOverride ||
method.IsImplicitlyDeclared ||
method.MethodKind != MethodKind.Ordinary)
method.MethodKind != MethodKind.Ordinary ||
serviceRegistrationsOnly && !IsServiceRegistrationMethod(method))
{
continue;
}
Expand All @@ -814,6 +832,10 @@ private List<MethodInfo> CollectMethods(INamedTypeSymbol type)

methods.Add(new MethodInfo
{
Signature = serviceRegistrationsOnly && syntax != null
? syntax.WithAttributeLists(default).WithBody(null).WithExpressionBody(null)
.WithSemicolonToken(default).WithoutTrivia().NormalizeWhitespace(indentation: "", eol: " ").ToFullString()
: null,
Name = method.Name,
ReturnType = method.ReturnType.ToDisplayString(TypeFormat),
Description = ResolveDescription(method),
Expand Down
7 changes: 7 additions & 0 deletions tools/BootstrapBlazor.LLMsDocsGenerator/ComponentInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ public class ComponentInfo

public bool SuppressSourceLink { get; set; }

public bool IsServiceRegistrationExtension { 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 Expand Up @@ -157,6 +159,11 @@ public class ParameterInfo
/// </summary>
public class MethodInfo
{
/// <summary>
/// Source signature for registration extensions, including defaults and generic constraints.
/// </summary>
public string? Signature { get; set; }

/// <summary>
/// Method name
/// </summary>
Expand Down
8 changes: 5 additions & 3 deletions tools/BootstrapBlazor.LLMsDocsGenerator/DocsGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,12 @@ public static async Task GenerateAllAsync(string outputFolder, string? project =
Logger($"Found {components.Count} components");
var categories = GetProjectCategories(components);
var services = await analyzer.AnalyzeProjectServicesAsync(components);
Logger($"Found {services.Count} services");
var registrationCount = services.Count(service => service.IsServiceRegistrationExtension);
Logger($"Found {services.Count - registrationCount} services");
Logger($"Found {registrationCount} service registration extensions");
if (components.Count == 0 && services.Count == 0)
{
throw new InvalidDataException("No components or services found in the project.");
throw new InvalidDataException("No components, services or service registration extensions found in the project.");
}

var duplicateComponent = components.GroupBy(component => component.Name, StringComparer.OrdinalIgnoreCase)
Expand Down Expand Up @@ -63,7 +65,7 @@ public static async Task GenerateAllAsync(string outputFolder, string? project =
var filePath = Path.Combine(componentsOutputPath, $"{type.Name}.txt");
await File.WriteAllTextAsync(filePath, content);
}
Logger($"Generated {components.Count} component and {services.Count} service files in {componentsOutputPath}");
Logger($"Generated {components.Count} component, {services.Count - registrationCount} service and {registrationCount} registration extension files in {componentsOutputPath}");
RemoveStaleDocuments(componentsOutputPath, components.Concat(services));

Logger("Documentation generation complete!");
Expand Down
33 changes: 29 additions & 4 deletions tools/BootstrapBlazor.LLMsDocsGenerator/MarkdownBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -157,13 +157,15 @@ void AppendComponentLink(ComponentInfo component)
}

// Injected services
if (services.Count > 0)
var serviceTypes = services.Where(service => !service.IsServiceRegistrationExtension).ToList();
var registrationExtensions = services.Where(service => service.IsServiceRegistrationExtension).ToList();
if (serviceTypes.Count > 0)
{
_sb.AppendLine("## 服务及相关接口");
_sb.AppendLine();
_sb.AppendLine("公开的服务和相关接口;并非所有接口都由依赖注入注册。");
_sb.AppendLine();
foreach (var service in services)
foreach (var service in serviceTypes)
{
var localized = Localize(service.Summary, lang);
var summary = !string.IsNullOrEmpty(localized) ? $" - {TruncateSummary(localized, 60)}" : "";
Expand All @@ -172,11 +174,28 @@ void AppendComponentLink(ComponentInfo component)
_sb.AppendLine();
}

if (registrationExtensions.Count > 0)
{
_sb.AppendLine("## 服务注册扩展");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚪ Low · Extensions get the wrong category

When the generated index is read by the CLI, LlmsDocsClient.ParseIndex recognizes only ### headings, so it leaves the category unchanged when it reaches this ## section and assigns that stale (or empty) category to the extension entries. Callers of ListAsync receive misleading category values.

Teach the index parser to assign a category to the service-registration section, or emit a heading level the parser recognizes.

Prompt for AI agents
In `tools/BootstrapBlazor.LLMsDocsGenerator/MarkdownBuilder.cs` at line 179:

**Extensions get the wrong category**

When the generated index is read by the CLI, `LlmsDocsClient.ParseIndex` recognizes only `###` headings, so it leaves the category unchanged when it reaches this `##` section and assigns that stale (or empty) category to the extension entries. Callers of `ListAsync` receive misleading category values.

Teach the index parser to assign a category to the service-registration section, or emit a heading level the parser recognizes.

_sb.AppendLine();
_sb.AppendLine("公开的 IServiceCollection 注册扩展方法;扩展类本身不是可注入的服务。");
_sb.AppendLine();
foreach (var extension in registrationExtensions)
{
_sb.AppendLine($"- [{extension.Name}](components/{extension.Name}.txt)");
}
_sb.AppendLine();
}

// Footer
_sb.AppendLine("---");
_sb.AppendLine($"生成时间: {DateTime.UtcNow:yyyy-MM-dd}");
_sb.AppendLine($"组件总数: {components.Count}");
_sb.AppendLine($"服务总数: {services.Count}");
_sb.AppendLine($"服务总数: {serviceTypes.Count}");
if (registrationExtensions.Count > 0)
{
_sb.AppendLine($"服务注册扩展类型总数: {registrationExtensions.Count}");
}

return _sb.ToString();
}
Expand Down Expand Up @@ -235,6 +254,12 @@ private static void BuildComponentSection(StringBuilder _sb, ComponentInfo compo
}
}

if (component.IsServiceRegistrationExtension)
{
_sb.AppendLine("此类型提供服务注册扩展方法,不是可注入的服务。外部服务接口及配置类型的 API 请查阅项目实际引用版本的文档。");
_sb.AppendLine();
}

// Service registration (DI): extension services must be registered before use.
if (component.Registrations.Count > 0)
{
Expand Down Expand Up @@ -348,7 +373,7 @@ private static void BuildComponentSection(StringBuilder _sb, ComponentInfo compo
foreach (var method in component.PublicMethods.OrderBy(m => m.Name))
{
var paramStr = string.Join(", ", method.Parameters.Select(p => $"{p.Item1} {p.Item2}"));
_sb.AppendLine($"- `{method.ReturnType} {method.Name}({paramStr})`");
_sb.AppendLine($"- `{method.Signature ?? $"{method.ReturnType} {method.Name}({paramStr})"}`");

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 · Generated docs accept injected Markdown

When an attacker contributes a registration extension with an optional raw-string default containing Markdown or HTML delimiters, BuildComponentSection writes the source signature inside a single-backtick code span without escaping it, so embedded backticks or raw-string newlines break out of the span and inject Markdown or HTML into generated documentation consumed by renderers or agents.

Escape the signature for Markdown or render it in a format that safely handles embedded backticks and newlines.

Prompt for AI agents
In `tools/BootstrapBlazor.LLMsDocsGenerator/MarkdownBuilder.cs` at line 376:

**Generated docs accept injected Markdown**

When an attacker contributes a registration extension with an optional raw-string default containing Markdown or HTML delimiters, `BuildComponentSection` writes the source signature inside a single-backtick code span without escaping it, so embedded backticks or raw-string newlines break out of the span and inject Markdown or HTML into generated documentation consumed by renderers or agents.

Escape the signature for Markdown or render it in a format that safely handles embedded backticks and newlines.

var methodDescription = Localize(method.Description, lang);
if (!string.IsNullOrEmpty(methodDescription))
{
Expand Down
5 changes: 4 additions & 1 deletion tools/BootstrapBlazor.LLMsDocsGenerator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ Without arguments, `llms-docs` analyzes the project in the current working direc
components\
MyComponent.txt
IExampleService.txt
ServiceCollectionExtensions.txt
```

`llms.txt` indexes the project's components and services using relative links. Each type has its own Markdown document, so an agent can load only the API it needs:
Expand All @@ -68,14 +69,16 @@ Without arguments, `llms-docs` analyzes the project in the current working direc
- Discoverable service registration methods
- Source links when the repository is recognized

Documentation uses Chinese text from bilingual XML comments, falling back to available text. Component-only and service-only projects are supported; generation fails if no supported types are found. Duplicate names that would overwrite files also cause generation to fail.
Documentation uses Chinese text from bilingual XML comments, falling back to available text. Component-only, service-only and registration-extension-only projects are supported; generation fails if no supported types are found. Duplicate names that would overwrite files also cause generation to fail.

The output directory is created if needed. Existing contents are not cleared; only stale `.txt` documents carrying the generator's marker are removed. Unmarked files and subdirectories are preserved.

## Analysis scope and limitations

The analyzer uses Roslyn to scan project source and collect `[Parameter]` properties, event callbacks, public methods and XML comments. Locally resolvable base members are included. Services are discovered from public, non-obsolete top-level types: interfaces under `Services`, interfaces ending in `Service` or `Provider`, and non-static classes ending in `Service` or `Provider`.

Public, non-obsolete top-level static classes containing public, non-obsolete `Add*` or `TryAdd*` extension methods on `IServiceCollection` are also included. Only those registration methods are documented, preserving their source signatures, including the `this` receiver, generic parameters and constraints, and optional defaults. They appear in a separate index section, not as injectable services. Receiver types are matched by name because dependency metadata is not loaded; external service interfaces, implementations and configuration types are not copied into the output.

This is source analysis, not a complete MSBuild or Razor compilation:

- External base members and service interfaces may be missing.
Expand Down
5 changes: 4 additions & 1 deletion tools/BootstrapBlazor.LLMsDocsGenerator/README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ llms-docs --project ".\src\MyComponents\MyComponents.csproj" --output ".\artifac
components\
MyComponent.txt
IExampleService.txt
ServiceCollectionExtensions.txt
```

`llms.txt` 使用相对链接索引工程中的组件与服务,每个类型各自生成一份 Markdown 文档,供 Agent 按需读取:
Expand All @@ -68,14 +69,16 @@ llms-docs --project ".\src\MyComponents\MyComponents.csproj" --output ".\artifac
- 可识别的服务注册方法
- 仓库可识别时的源码链接

文档优先提取双语 XML 注释中的中文,无中文时使用已有文本。支持只有组件或只有服务的工程;未找到可识别的类型时生成失败。类型名称冲突可能覆盖文件时也会报错。
文档优先提取双语 XML 注释中的中文,无中文时使用已有文本。支持只有组件、只有服务或只有服务注册扩展的工程;未找到可识别的类型时生成失败。类型名称冲突可能覆盖文件时也会报错。

输出目录不存在时自动创建,不会清空已有内容;仅清理带有生成器标记的过期 `.txt` 文档,保留无标记文件及子目录。

## 分析范围与限制

分析器使用 Roslyn 扫描工程源码,提取 `[Parameter]` 属性、事件回调、公开方法和 XML 注释,并收录本地可解析的继承成员。服务从公开、非过时的顶层类型中发现:`Services` 目录下的接口、以 `Service` 或 `Provider` 结尾的接口,以及以 `Service` 或 `Provider` 结尾的非静态类。

同时收录公开、非过时的顶层静态类中,针对 `IServiceCollection` 的公开、非过时 `Add*` 或 `TryAdd*` 扩展方法。只提取这些注册方法,保留源码签名中的 `this` 接收参数、泛型参数及约束、可选参数默认值。注册扩展在索引中单独分组,不会作为可注入服务展示。由于不加载依赖元数据,接收参数类型按名称匹配;外部服务接口、实现及配置类型不会复制到输出中。

这是源码分析,不是完整的 MSBuild 或 Razor 编译:

- 外部基类成员与服务接口可能未收录。
Expand Down
Loading