From 7fc2c52892813d788558fc340e212ccbcabbd24d Mon Sep 17 00:00:00 2001 From: Argo Zhang Date: Tue, 17 Nov 2026 08:28:45 +0800 Subject: [PATCH 1/2] =?UTF-8?q?chore:=20=E6=9B=B4=E6=96=B0=20Docs=20?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E6=94=AF=E6=8C=81=E6=8C=89=E9=A1=B9=E7=9B=AE?= =?UTF-8?q?=E7=94=9F=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ArgumentsHelper.cs | 26 +- .../ComponentAnalyzer.cs | 63 +++- .../ComponentInfo.cs | 2 + .../DocsGenerator.cs | 212 +++----------- .../MarkdownBuilder.cs | 132 +-------- .../README.md | 268 ++++------------- .../README.zh-CN.md | 269 ++++-------------- 7 files changed, 215 insertions(+), 757 deletions(-) diff --git a/tools/BootstrapBlazor.LLMsDocsGenerator/ArgumentsHelper.cs b/tools/BootstrapBlazor.LLMsDocsGenerator/ArgumentsHelper.cs index b7888df7..a8b705d5 100644 --- a/tools/BootstrapBlazor.LLMsDocsGenerator/ArgumentsHelper.cs +++ b/tools/BootstrapBlazor.LLMsDocsGenerator/ArgumentsHelper.cs @@ -12,42 +12,36 @@ internal static class ArgumentsHelper public static ParseResult Parse(string[] args) { const string defaultFolder = "."; - var rootFolderOption = new Option("--root") - { - Description = "Set the Server project folder (core-only can instead run from the core project)" - }; var outputFolderOption = new Option("--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("--core-only") + var projectOption = new Option("--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); diff --git a/tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs b/tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs index fb99d395..b6d627ac 100644 --- a/tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs +++ b/tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs @@ -28,6 +28,8 @@ public partial class ComponentAnalyzer private readonly string? _samplesPath; private readonly string? _extensionsSourcePath; private readonly IReadOnlyDictionary? _extensionProjects; + private readonly bool _singleProject; + private readonly string? _extensionRepository; private CSharpCompilation? _compilation; private readonly Dictionary _treeByPath = new(StringComparer.OrdinalIgnoreCase); @@ -52,10 +54,13 @@ public ComponentAnalyzer(string sourcePath, string? extensionsSourcePath = null, } internal ComponentAnalyzer(string sourcePath, string? extensionsSourcePath, - IReadOnlyDictionary? extensionProjects, bool includeSamples) + IReadOnlyDictionary? extensionProjects, bool includeSamples, bool singleProject = false) { _sourcePath = sourcePath; - _componentsPath = Path.Combine(sourcePath, "Components"); + _singleProject = singleProject; + _componentsPath = singleProject ? sourcePath : Path.Combine(sourcePath, "Components"); + _extensionRepository = singleProject + ? FindExtensionRepository(sourcePath) : null; _samplesPath = includeSamples ? Path.Combine(Path.GetDirectoryName(sourcePath)!, "BootstrapBlazor.Server", "Components", "Samples") : null; @@ -86,6 +91,7 @@ public async Task> 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(StringComparer.Ordinal); @@ -93,7 +99,7 @@ public async Task> AnalyzeAllComponentsAsync() 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); } @@ -119,7 +125,7 @@ public async Task> 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); } @@ -226,7 +232,7 @@ public async Task> AnalyzeServicesAsync(IEnumerable return services; } - internal async Task> AnalyzeCoreServicesAsync(IEnumerable components) + internal async Task> AnalyzeProjectServicesAsync(IEnumerable components) { await EnsureCompilationAsync(); @@ -240,7 +246,7 @@ internal async Task> AnalyzeCoreServicesAsync(IEnumerable> AnalyzeCoreServicesAsync(IEnumerable> AnalyzeCoreServicesAsync(IEnumerable> AnalyzeCoreServicesAsync(IEnumerable 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) @@ -574,6 +592,11 @@ private static List ReadProjectUsings(string projectDirect private async Task 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)))) + { + return null; + } string? baseType = null; string? ns = null; @@ -601,10 +624,11 @@ private static List 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"; @@ -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, LastModified = File.GetLastWriteTimeUtc(filePath), SamplePath = FindSamplePath(symbol.Name), Parameters = CollectParameters(symbol), @@ -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). @@ -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); @@ -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)) diff --git a/tools/BootstrapBlazor.LLMsDocsGenerator/ComponentInfo.cs b/tools/BootstrapBlazor.LLMsDocsGenerator/ComponentInfo.cs index a394d565..223bf288 100644 --- a/tools/BootstrapBlazor.LLMsDocsGenerator/ComponentInfo.cs +++ b/tools/BootstrapBlazor.LLMsDocsGenerator/ComponentInfo.cs @@ -66,6 +66,8 @@ public class ComponentInfo /// public bool IsExtension { get; set; } + public bool SuppressSourceLink { get; set; } + /// /// Dependency-injection registration for an extension service, resolved from the /// AddXxx(this IServiceCollection) extension method that registers this type. diff --git a/tools/BootstrapBlazor.LLMsDocsGenerator/DocsGenerator.cs b/tools/BootstrapBlazor.LLMsDocsGenerator/DocsGenerator.cs index 551941e0..01ca0bc6 100644 --- a/tools/BootstrapBlazor.LLMsDocsGenerator/DocsGenerator.cs +++ b/tools/BootstrapBlazor.LLMsDocsGenerator/DocsGenerator.cs @@ -3,186 +3,92 @@ // See the LICENSE file in the project root for more information. // Maintainer: Argo Zhang(argo@live.ca) Website: https://www.blazor.zone -using System.Xml.Linq; - namespace BootstrapBlazorLLMsDocsGenerator; internal static class DocsGenerator { /// - /// Generate all documentation files + /// Generate all documentation files for one project. /// - public static async Task GenerateAllAsync(string? rootFolder, string outputFolder, bool coreOnly = false) + public static async Task GenerateAllAsync(string outputFolder, string? project = null) { - var _sourcePath = GetSourcePath(rootFolder, coreOnly); - var _outputPath = coreOnly ? outputFolder : Path.Combine(outputFolder, "wwwroot", "llms"); - - Logger($"Source path: {_sourcePath}"); - Logger($"Output path: {_outputPath}"); - - if (!Directory.Exists(_sourcePath)) + var sourcePath = GetSourcePath(project); + var projectFiles = Directory.GetFiles(sourcePath, "*.csproj"); + if (projectFiles.Length != 1) { - throw new DirectoryNotFoundException($"Core source directory not found: {_sourcePath}"); + throw new InvalidDataException($"Expected one project in {sourcePath}, found {projectFiles.Length}."); } + var packageName = Path.GetFileNameWithoutExtension(projectFiles[0]); + Logger($"Source path: {sourcePath}"); + Logger($"Output path: {outputFolder}"); Logger("Analyzing components..."); - var extensionsSrc = string.Empty; - if (!coreOnly) - { - var coreRepoRoot = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetFullPath(_sourcePath)))!; - extensionsSrc = Path.Combine(Path.GetDirectoryName(coreRepoRoot)!, "BootstrapBlazor.Extensions", "src"); - } - var hasExtensions = !coreOnly && Directory.Exists(extensionsSrc); - - var extensionProjects = hasExtensions - ? ReadExtensionProjects(Path.GetDirectoryName(extensionsSrc)!) - : new Dictionary(StringComparer.OrdinalIgnoreCase); - var _analyzer = new ComponentAnalyzer(_sourcePath, hasExtensions ? extensionsSrc : null, - extensionProjects, includeSamples: !coreOnly); - var components = await _analyzer.AnalyzeAllComponentsAsync(); + var projects = new Dictionary(StringComparer.OrdinalIgnoreCase) { [packageName] = sourcePath }; + var analyzer = new ComponentAnalyzer(sourcePath, null, projects, includeSamples: false, singleProject: true); + var components = await analyzer.AnalyzeAllComponentsAsync(); Logger($"Found {components.Count} components"); - if (components.Count == 0) - { - throw new InvalidDataException("No core components found."); - } - - CategoryProvider? provider = null; - if (!coreOnly) - { - var serverPath = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(_sourcePath))!, "BootstrapBlazor.Server"); - provider = new CategoryProvider(serverPath); - } - - var categories = coreOnly ? GetCoreCategories(components) : provider!.Parse(); - Logger($"Found {categories.Count} categories"); - var services = coreOnly - ? await _analyzer.AnalyzeCoreServicesAsync(components) - : await _analyzer.AnalyzeServicesAsync(provider!.ParseServices()); + var categories = GetProjectCategories(components); + var services = await analyzer.AnalyzeProjectServicesAsync(components); Logger($"Found {services.Count} services"); - if (services.Count == 0) - { - throw new InvalidDataException("No core services found."); - } - - if (coreOnly) + if (components.Count == 0 && services.Count == 0) { - var duplicateComponent = components.GroupBy(component => component.Name, StringComparer.OrdinalIgnoreCase) - .FirstOrDefault(group => group.Skip(1).Any()); - if (duplicateComponent != null) - { - throw new InvalidDataException($"Core component names collide: {duplicateComponent.Key}"); - } - - var componentNames = components.Select(component => component.Name).ToHashSet(StringComparer.OrdinalIgnoreCase); - var duplicate = services.FirstOrDefault(service => componentNames.Contains(service.Name)); - if (duplicate != null) - { - throw new InvalidDataException($"Core component and service names collide: {duplicate.Name}"); - } + throw new InvalidDataException("No components or services found in the project."); } - var configuredPackages = coreOnly ? new List() : provider!.ParseExtensions(); - if (!hasExtensions && configuredPackages.Count > 0) + var duplicateComponent = components.GroupBy(component => component.Name, StringComparer.OrdinalIgnoreCase) + .FirstOrDefault(group => group.Skip(1).Any()); + if (duplicateComponent != null) { - throw new DirectoryNotFoundException($"Extension sources required by docs.json were not found: {extensionsSrc}"); + throw new InvalidDataException($"Component names collide: {duplicateComponent.Key}"); } - var extPackages = configuredPackages.Where(package => - { - if (extensionProjects.ContainsKey(package.Name)) - { - return true; - } - - Console.Error.WriteLine($"Skipping extension package not in the solution: {package.Name}"); - return false; - }).ToList(); - var extComponents = hasExtensions - ? await _analyzer.AnalyzeTypesByNameAsync(extPackages.SelectMany(p => p.Components).Distinct()) - : new List(); - var extServices = hasExtensions - ? await _analyzer.AnalyzeTypesByNameAsync(extPackages.SelectMany(p => p.Services).Distinct(), - resolveRegistration: true, registrationPackages: extPackages) - : new List(); - Logger($"Found {extComponents.Count} extension components, {extServices.Count} extension services"); - - // A service can be both a core built-in (default implementation, registered by - // AddBootstrapBlazor) and provided by an extension package as an alternative - // implementation — e.g. IHtml2Pdf. Keep only the extension entry (it carries the - // registration call) and drop the duplicate from the built-in service list. - var extServiceNames = extServices.Select(s => s.Name).ToHashSet(StringComparer.Ordinal); - var removed = services.RemoveAll(s => extServiceNames.Contains(s.Name)); - if (removed > 0) + var componentNames = components.Select(component => component.Name).ToHashSet(StringComparer.OrdinalIgnoreCase); + var duplicate = services.FirstOrDefault(service => componentNames.Contains(service.Name)); + if (duplicate != null) { - Logger($"De-duplicated {removed} service(s) also provided by extension packages"); + throw new InvalidDataException($"Component and service names collide: {duplicate.Name}"); } - // Chinese documentation only: the index at the docs root and one file per - // component (Chinese text extracted from the bilingual blocks) under - // the components/ directory. - Directory.CreateDirectory(_outputPath); - var indexPath = Path.Combine(_outputPath, "llms.txt"); - await File.WriteAllTextAsync(indexPath, MarkdownBuilder.BuildIndexDoc(components, categories, services, extComponents, extServices, extPackages, "zh", coreOnly)); + Directory.CreateDirectory(outputFolder); + var indexPath = Path.Combine(outputFolder, "llms.txt"); + await File.WriteAllTextAsync(indexPath, MarkdownBuilder.BuildIndexDoc(components, categories, services, "zh", packageName)); Logger($"Generated: {indexPath}"); - var componentsOutputPath = Path.Combine(_outputPath, "components"); + var componentsOutputPath = Path.Combine(outputFolder, "components"); Directory.CreateDirectory(componentsOutputPath); - foreach (var component in components) - { - var content = MarkdownBuilder.BuildComponentDoc(component, "zh"); - var filePath = Path.Combine(componentsOutputPath, $"{component.Name}.txt"); - await File.WriteAllTextAsync(filePath, content); - } - foreach (var service in services) + foreach (var type in components.Concat(services)) { - var content = MarkdownBuilder.BuildComponentDoc(service, "zh"); - var filePath = Path.Combine(componentsOutputPath, $"{service.Name}.txt"); + var content = MarkdownBuilder.BuildComponentDoc(type, "zh"); + 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}"); - - // Extension components & services go into a separate extensions/ directory. - if (extComponents.Count > 0 || extServices.Count > 0) - { - var extOutputPath = Path.Combine(_outputPath, "extensions"); - Directory.CreateDirectory(extOutputPath); - foreach (var item in extComponents.Concat(extServices)) - { - var content = MarkdownBuilder.BuildComponentDoc(item, "zh"); - var filePath = Path.Combine(extOutputPath, $"{item.Name}.txt"); - await File.WriteAllTextAsync(filePath, content); - } - Logger($"Generated {extComponents.Count + extServices.Count} extension files in {extOutputPath}"); - } - RemoveStaleDocuments(componentsOutputPath, components.Concat(services)); - RemoveStaleDocuments(Path.Combine(_outputPath, "extensions"), extComponents.Concat(extServices)); Logger("Documentation generation complete!"); } - private static string GetSourcePath(string? rootFolder, bool coreOnly) + private static string GetSourcePath(string? project) { - if (coreOnly && rootFolder == null) + if (project == null) { - var current = Directory.GetCurrentDirectory(); - if (File.Exists(Path.Combine(current, "BootstrapBlazor.csproj"))) - { - return current; - } - - var repositorySource = Path.Combine(current, "src", "BootstrapBlazor"); - if (File.Exists(Path.Combine(repositorySource, "BootstrapBlazor.csproj"))) - { - return repositorySource; - } + return Directory.GetCurrentDirectory(); } - return Path.Combine(rootFolder ?? ".", "..", "BootstrapBlazor"); + var path = Path.GetFullPath(project); + if (File.Exists(path) && path.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase)) + { + return Path.GetDirectoryName(path)!; + } + if (Directory.Exists(path)) + { + return path; + } + throw new FileNotFoundException($"Project not found: {path}"); } - private static List GetCoreCategories(IEnumerable components) + private static List GetProjectCategories(IEnumerable components) { return components .Select(component => (Component: component, Parts: component.SourcePath.Split('/'))) @@ -197,34 +103,6 @@ private static List GetCoreCategories(IEnumerable ReadExtensionProjects(string repositoryRoot) - { - var solutionPath = Path.Combine(repositoryRoot, "BootstrapBlazor.Extensions.slnx"); - var solution = XDocument.Load(solutionPath); - var sourceRoot = Path.GetFullPath(Path.Combine(repositoryRoot, "src")) + Path.DirectorySeparatorChar; - var projects = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (var project in solution.Descendants("Project")) - { - var relativePath = (string?)project.Attribute("Path") - ?? throw new InvalidDataException($"Project without a path in {solutionPath}"); - var projectPath = Path.GetFullPath(Path.Combine(repositoryRoot, - relativePath.Replace('/', Path.DirectorySeparatorChar))); - if (!projectPath.StartsWith(sourceRoot, StringComparison.OrdinalIgnoreCase)) - { - continue; - } - - if (!File.Exists(projectPath)) - { - throw new FileNotFoundException("Extension solution project not found.", projectPath); - } - - projects.Add(Path.GetFileNameWithoutExtension(projectPath), Path.GetDirectoryName(projectPath)!); - } - - return projects; - } - private static void RemoveStaleDocuments(string directory, IEnumerable types) { if (!Directory.Exists(directory)) diff --git a/tools/BootstrapBlazor.LLMsDocsGenerator/MarkdownBuilder.cs b/tools/BootstrapBlazor.LLMsDocsGenerator/MarkdownBuilder.cs index 8b835d8b..6ae9d0d7 100644 --- a/tools/BootstrapBlazor.LLMsDocsGenerator/MarkdownBuilder.cs +++ b/tools/BootstrapBlazor.LLMsDocsGenerator/MarkdownBuilder.cs @@ -14,9 +14,7 @@ namespace BootstrapBlazorLLMsDocsGenerator; internal static partial class MarkdownBuilder { private const string GitHubRawBaseUrl = "https://raw.githubusercontent.com/dotnetcore/BootstrapBlazor/refs/heads/main/"; - private const string GitHubRepositoryUrl = "https://github.com/dotnetcore/BootstrapBlazor"; private const string GitHubExtensionsRawUrl = "https://raw.githubusercontent.com/BootstrapBlazor/BootstrapBlazor.Extensions/refs/heads/master/"; - private const string GitHubExtensionsRepositoryUrl = "https://github.com/BootstrapBlazor/BootstrapBlazor.Extensions"; /// /// Extract the text for a single language from a doc string that may contain @@ -89,37 +87,19 @@ private static string CleanInlineMarkup(string text) [GeneratedRegex("\\s+")] private static partial Regex WhitespaceRegex(); - public static string BuildIndexDoc(List components, List categories, List services, List extensionComponents, List extensionServices, List extensionPackages, string lang, bool coreOnly = false) + public static string BuildIndexDoc(List components, List categories, List services, string lang, string projectName) { var _sb = new StringBuilder(); - _sb.AppendLine("# BootstrapBlazor"); + _sb.AppendLine($"# {projectName}"); _sb.AppendLine(); - _sb.AppendLine("> 基于 Bootstrap 5 的企业级 Blazor UI 组件库"); + _sb.AppendLine("> 本文档仅分析当前工程源码;外部基类、外部服务接口及 Razor @code 中的成员可能未收录。"); _sb.AppendLine(); // Quick Start section _sb.AppendLine("## 快速开始"); _sb.AppendLine(); _sb.AppendLine("```bash"); - _sb.AppendLine("dotnet add package BootstrapBlazor"); - _sb.AppendLine("```"); - _sb.AppendLine(); - _sb.AppendLine("### 配置"); - _sb.AppendLine(); - _sb.AppendLine("```csharp"); - _sb.AppendLine("// Program.cs"); - _sb.AppendLine("builder.Services.AddBootstrapBlazor();"); - _sb.AppendLine("```"); - _sb.AppendLine(); - _sb.AppendLine("```razor"); - _sb.AppendLine("@* _Imports.razor *@"); - _sb.AppendLine("@using BootstrapBlazor.Components"); - _sb.AppendLine("```"); - _sb.AppendLine(); - _sb.AppendLine("```html"); - _sb.AppendLine(""); - _sb.AppendLine(""); - _sb.AppendLine(""); + _sb.AppendLine($"dotnet add package {projectName}"); _sb.AppendLine("```"); _sb.AppendLine(); @@ -130,8 +110,6 @@ public static string BuildIndexDoc(List components, List c.Name, StringComparer.Ordinal) .ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal); @@ -166,7 +144,6 @@ void AppendComponentLink(ComponentInfo component) _sb.AppendLine(); } - // Anything not listed in docs.json falls back to "Other". var others = components.Where(c => !used.Contains(c.Name)).OrderBy(c => c.Name).ToList(); if (others.Count > 0) { @@ -182,11 +159,9 @@ void AppendComponentLink(ComponentInfo component) // Injected services if (services.Count > 0) { - _sb.AppendLine(coreOnly ? "## 核心服务及相关接口" : "## 内置服务"); + _sb.AppendLine("## 服务及相关接口"); _sb.AppendLine(); - _sb.AppendLine(coreOnly - ? "核心服务和相关公开接口,每个类型在 `components/` 目录下都有独立的文档文件;并非所有接口都由默认依赖注入注册。" - : "通过依赖注入使用的服务,每个服务在 `components/` 目录下都有独立的文档文件。"); + _sb.AppendLine("公开的服务和相关接口;并非所有接口都由依赖注入注册。"); _sb.AppendLine(); foreach (var service in services) { @@ -197,104 +172,11 @@ void AppendComponentLink(ComponentInfo component) _sb.AppendLine(); } - // Extension components & services (from BootstrapBlazor.Extensions) - void AppendExtensionLink(ComponentInfo item) - { - var localized = Localize(item.Summary, lang); - var s = !string.IsNullOrEmpty(localized) ? $" - {TruncateSummary(localized, 60)}" : ""; - _sb.AppendLine($"- [{item.Name}](extensions/{item.Name}.txt){s}"); - } - - // Group extension items under their owning package (docs.json "extensions" - // order), so the index mirrors the per-package layout of the source repo. - void AppendExtensionByPackage(List items, Func> selector) - { - var byName = items - .GroupBy(c => c.Name, StringComparer.Ordinal) - .ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal); - - foreach (var pkg in extensionPackages) - { - var members = selector(pkg) - .Where(byName.ContainsKey) - .Select(n => byName[n]) - .ToList(); - if (members.Count == 0) - { - continue; - } - - _sb.AppendLine($"### {pkg.Name}"); - _sb.AppendLine(); - foreach (var item in members) - { - AppendExtensionLink(item); - } - _sb.AppendLine(); - } - } - - if (extensionComponents.Count > 0) - { - _sb.AppendLine("## 扩展组件"); - _sb.AppendLine(); - _sb.AppendLine("来自 BootstrapBlazor.Extensions 扩展库的组件,按扩展包分组,每个在 `extensions/` 目录下都有独立的文档文件。"); - _sb.AppendLine(); - AppendExtensionByPackage(extensionComponents, p => p.Components); - } - - if (extensionServices.Count > 0) - { - _sb.AppendLine("## 扩展服务"); - _sb.AppendLine(); - _sb.AppendLine("来自 BootstrapBlazor.Extensions 扩展库的服务,按扩展包分组,每个在 `extensions/` 目录下都有独立的文档文件。"); - _sb.AppendLine(); - AppendExtensionByPackage(extensionServices, p => p.Services); - } - - // Source Code Reference - _sb.AppendLine("## 源码参考"); - _sb.AppendLine(); - _sb.AppendLine($"GitHub 仓库: {GitHubRepositoryUrl}"); - _sb.AppendLine(); - _sb.AppendLine("当文档不足时,请查阅源码:"); - _sb.AppendLine(); - _sb.AppendLine("### 文件结构"); - _sb.AppendLine(); - _sb.AppendLine("```"); - _sb.AppendLine($"{GitHubRawBaseUrl}/src/BootstrapBlazor/Components/{{ComponentName}}/"); - _sb.AppendLine("├── {Component}.razor # Razor 模板"); - _sb.AppendLine("├── {Component}.razor.cs # 组件逻辑与参数"); - _sb.AppendLine("├── {Component}Base.cs # 基类(如果存在)"); - _sb.AppendLine("├── {Component}Option.cs # 配置选项"); - _sb.AppendLine("└── {Component}Service.cs # 服务类(Dialog、Toast 等)"); - _sb.AppendLine("```"); - _sb.AppendLine(); - _sb.AppendLine("### 示例"); - _sb.AppendLine(); - _sb.AppendLine("```"); - _sb.AppendLine($"{GitHubRawBaseUrl}src/BootstrapBlazor.Server/Components/Samples/{{ComponentName}}s.razor"); - _sb.AppendLine("```"); - _sb.AppendLine(); - _sb.AppendLine("### 读取组件参数"); - _sb.AppendLine(); - _sb.AppendLine("查找带有 `[Parameter]` 特性的属性:"); - _sb.AppendLine(); - _sb.AppendLine("```csharp"); - _sb.AppendLine("/// "); - _sb.AppendLine("/// 获得/设置 是否显示工具栏"); - _sb.AppendLine("/// "); - _sb.AppendLine("[Parameter]"); - _sb.AppendLine("public bool ShowToolbar { get; set; }"); - _sb.AppendLine("```"); - _sb.AppendLine(); - // Footer _sb.AppendLine("---"); _sb.AppendLine($"生成时间: {DateTime.UtcNow:yyyy-MM-dd}"); _sb.AppendLine($"组件总数: {components.Count}"); _sb.AppendLine($"服务总数: {services.Count}"); - _sb.AppendLine($"仓库地址: {GitHubRepositoryUrl}"); return _sb.ToString(); } @@ -482,7 +364,7 @@ private static void BuildComponentSection(StringBuilder _sb, ComponentInfo compo } // Source reference with GitHub URLs - if (!string.IsNullOrEmpty(component.SourcePath)) + if (!component.SuppressSourceLink && !string.IsNullOrEmpty(component.SourcePath)) { _sb.AppendLine("### 源码"); _sb.AppendLine(); diff --git a/tools/BootstrapBlazor.LLMsDocsGenerator/README.md b/tools/BootstrapBlazor.LLMsDocsGenerator/README.md index 8e5f57b5..15ad433e 100644 --- a/tools/BootstrapBlazor.LLMsDocsGenerator/README.md +++ b/tools/BootstrapBlazor.LLMsDocsGenerator/README.md @@ -2,264 +2,94 @@ English | [简体中文](./README.zh-CN.md) -A .NET tool that automatically generates LLM-friendly documentation for BootstrapBlazor components. - -## Purpose - -AI coding assistants (Claude Code, Cursor, GitHub Copilot) often generate incorrect UI code because they lack accurate component API information. This tool solves that problem by: - -1. **Auto-generating parameter tables** from source code using Roslyn -2. **Providing GitHub source links** for deeper reference -3. **Producing one file per component** so agents load only the API they need - -## Architecture - -``` -┌─────────────────────────────────────────────────────────────┐ -│ BootstrapBlazor.LLMsDocsGenerator │ -├─────────────────────────────────────────────────────────────┤ -│ ComponentAnalyzer → Roslyn-based source code parser │ -│ MarkdownBuilder → Generates markdown documentation │ -│ DocsGenerator → Orchestrates the generation flow │ -└─────────────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────┐ -│ Default output: /wwwroot/llms/ │ -├─────────────────────────────────────────────────────────────┤ -│ llms.txt → Index with quick start guide │ -│ components/ → Individual component documentation │ -│ ├── Button.txt → Button component API reference │ -│ ├── Table.txt → Table component API reference │ -│ ├── Select.txt → Select component API reference │ -│ └── ... → One file per component │ -│ extensions/ → BootstrapBlazor.Extensions docs │ -│ ├── SelectCity.txt → Extension component API reference │ -│ └── ... → One file per extension type │ -└─────────────────────────────────────────────────────────────┘ -``` - -With `--core-only`, the output directory is `` itself. - -### Why One File Per Component? - -This design optimizes for LLM and Code Agent consumption: - -| Aspect | Per-Category (Old) | Per-Component (New) | -|--------|-------------------|---------------------| -| **Precision** | ❌ Loads unrelated components | ✅ Only needed API info | -| **Token Efficiency** | ❌ Wastes tokens on irrelevant data | ✅ Minimal context loading | -| **Cache Friendly** | ❌ Regenerates entire category | ✅ Updates single file | -| **RAG Retrieval** | ❌ Coarse-grained matches | ✅ Fine-grained matches | - -## How It Works - -### 1. Source Code Analysis - -The `ComponentAnalyzer` uses Roslyn to parse C# source files, scanning properties marked with the `[Parameter]` attribute and extracting their XML documentation comments. Public components defined in plain `.cs` files are discovered through their `ComponentBase` or `IComponent` inheritance chain. - -### 2. Documentation Generation - -The `MarkdownBuilder` creates structured markdown with: - -- Parameter tables (name, type, default, description) -- Event callbacks section -- Public methods -- GitHub source links - -### 3. Component Organization - -Components are organized in the index by category for easy navigation, but each component has its own dedicated documentation file: - -| Category | Example Components | -|----------|-------------------| -| table | Table, SelectTable, TableToolbar | -| input | BootstrapInput, Textarea, OtpInput | -| select | Select, AutoComplete, Cascader | -| button | Button, PopConfirmButton | -| dialog | Modal, Drawer, Toast | -| nav | Menu, Tab, Breadcrumb | -| card | Card, Collapse, GroupBox | -| treeview | TreeView, Tree | -| form | ValidateForm, EditorForm | -| other | All other components | +A .NET tool that generates LLM-friendly API documentation from a project's component and service source code. Single-project generation requires only the target project, with no sibling repository required. ## Requirements -- An SDK matching the project's `TargetFrameworks` (currently .NET 11 for source builds). -- A local `BootstrapBlazor` checkout; unless using `--core-only`, when `docs.json` configures extension packages, also check out `BootstrapBlazor.Extensions` beside it. The generator does not clone repositories. +- An SDK matching the tool project's target framework (currently .NET 11 for source builds). +- The target project's `.csproj` and source files. ## Installation -### Run from source - -From the `BootstrapBlazor.Extensions` repository root: +Pack from this repository's root and install the tool: ```powershell -dotnet run --project tools\BootstrapBlazor.LLMsDocsGenerator --root "..\BootstrapBlazor\src\BootstrapBlazor.Server" --output "..\BootstrapBlazor\src\BootstrapBlazor.Server" -``` - -### Install as a global tool - -Pack and install from the local build output: - -```bash -dotnet pack tools/BootstrapBlazor.LLMsDocsGenerator -c Release -dotnet tool install --global --add-source ./tools/BootstrapBlazor.LLMsDocsGenerator/bin/Release BootstrapBlazor.LLMsDocsGenerator +dotnet pack tools\BootstrapBlazor.LLMsDocsGenerator -c Release +dotnet tool install --global --add-source .\tools\BootstrapBlazor.LLMsDocsGenerator\bin\Release BootstrapBlazor.LLMsDocsGenerator ``` -Update / uninstall: +Update or uninstall: -```bash +```powershell dotnet tool update --global BootstrapBlazor.LLMsDocsGenerator dotnet tool uninstall --global BootstrapBlazor.LLMsDocsGenerator ``` -Once installed, the tool is invoked with the command name `llms-docs`. - -## Usage - -The output defaults to the current working directory (`.`). In default mode, the root also defaults to `.`; run `llms-docs` from BB's `src/BootstrapBlazor.Server` directory to write documentation into that project. With `--core-only`, run from the core project or repository root without specifying `--root`, and output is written directly to the `--output` directory without clearing existing contents. Overriding `--root` does not change the default `--output`. - -From the Server project directory, `dotnet llms-docs --output=bin\Release\publish\` also works: the omitted `--root` defaults to `.`, and relative output paths are resolved from that same directory. MSBuild can use `dotnet llms-docs --output=$(PublishDir)` when the path contains no spaces. +The command name is `llms-docs`. -| Option | Required | Description | -|--------|----------|-------------| -| `--root` | No | Server project folder. When specified, core source is read from `/../BootstrapBlazor`. Default mode uses `.`; core-only can discover the core project from the current core project, repository root, or Server directory. | -| `--output` | No | Output folder. Defaults to `.`. Default mode writes to `/wwwroot/llms/`; `--core-only` writes directly to `/`. | -| `--core-only` | No | Generate only core components and built-in services for BootstrapBlazor packaging. Defaults to `false`; extension configuration and sources are not analyzed. | +## Single-project usage -When a `BootstrapBlazor.Extensions` checkout is available beside the core `BootstrapBlazor` checkout, the generator also analyzes the extension sources. The extension types to document are configured under `extensions` in `src/BootstrapBlazor.Server/docs.json`, the only configuration location. Generation fails if the file is missing. Extension docs are written to `extensions/`. - -Only source projects listed in `BootstrapBlazor.Extensions.slnx` are scanned. Package names are matched against project filenames, not directory names. Configured packages outside the solution are skipped with a diagnostic; missing solution projects are reported as errors. Leftover directories do not participate in analysis. Core Razor-only components with an `@inherits` directive are also supported. In default mode, regeneration removes obsolete `.txt` files carrying the generator's `` marker, while preserving other files. - -If extension packages are configured but the sibling extension source checkout is missing, generation fails before changing existing documentation. Unresolved configured component or service types also fail generation before writing files or removing stale documents. Services shared by multiple packages retain one document listing the registration method for each configured package; choose the registration matching the package in use. - -With `--core-only`, no Server `docs.json`, sample files, extension checkout or solution is read. Component index groups are derived from the first directory under `Components`. Services are discovered from public, non-obsolete top-level types: interfaces under `Services`, and interfaces ending in `Service` or `Provider` under `Components`; public non-static classes ending in `Service` in either directory are also included unless already recognized as components. These are service-related APIs, not necessarily DI registrations. Duplicate names that would overwrite documentation cause generation to fail. No extension documents or extension index sections/links are generated. The output is `/llms.txt` and `/components/*.txt`, with relative index links suitable for a package. The output directory is created if needed; existing contents are not cleared. Stale files carrying the generator marker are removed while unmarked files and subdirectories are preserved. - -Explicit `` items in each source project's `.csproj` (including aliases and static imports) are applied to that project's C# files, without leaking these imports into other projects in the combined analysis. - -This is source analysis, not a full MSBuild evaluation: conditions, property expansion, imported `.props`/`.targets`, and `Using Remove` are not evaluated. Razor-only support synthesizes inheritance declarations; it does not compile Razor or extract members from `@code` blocks. - -Declare extension services by the types actually registered for injection. For example, both speech packages use `"services": ["IRecognizerProvider", "ISynthesizerProvider"]`, not their provider implementation classes. - -Generation errors and explicitly empty paths return a nonzero process exit code so MSBuild and CI can stop. - -Build the tool and run the core-only integration checks with PowerShell 7: +Run from the target project's directory: ```powershell -dotnet build .\tools\BootstrapBlazor.LLMsDocsGenerator -c Release -.\tools\BootstrapBlazor.LLMsDocsGenerator\tests\Verify-CoreOnly.ps1 +llms-docs --output ".\artifacts\llms" ``` -### Example - -With the `BootstrapBlazor` and `BootstrapBlazor.Extensions` repositories checked out as sibling directories, run from the `BootstrapBlazor` repository root and point both options at the server project: - -```bash -llms-docs --root src/BootstrapBlazor.Server --output src/BootstrapBlazor.Server -``` - -This reads components from `src/BootstrapBlazor` and produces: - -``` -src/BootstrapBlazor.Server/wwwroot/llms/llms.txt -src/BootstrapBlazor.Server/wwwroot/llms/components/*.txt -src/BootstrapBlazor.Server/wwwroot/llms/extensions/*.txt -``` - -The index groups extension docs by package, for example `BootstrapBlazor.Region`; `SelectCity` is generated as `extensions/SelectCity.txt`. - -From the same `BootstrapBlazor` repository root, run the sibling source project: +Or specify the project from another directory: ```powershell -dotnet run --project "..\BootstrapBlazor.Extensions\tools\BootstrapBlazor.LLMsDocsGenerator" --root "src\BootstrapBlazor.Server" --output "src\BootstrapBlazor.Server" +llms-docs --project ".\src\MyComponents\MyComponents.csproj" --output ".\artifacts\llms" ``` -### BootstrapBlazor NuGet packaging - -From the `BootstrapBlazor` repository root, generate core-only documentation directly into the skill references directory: - -```powershell -dotnet llms-docs --core-only --output "src\BootstrapBlazor\skills\bb-api\references" -``` +`--project` also accepts a directory containing exactly one `.csproj`. -No `docs.json` is needed. BootstrapBlazor.Server publishing must omit `--core-only` to keep the full website index, core documentation and extension documentation; its existing command and output paths are unchanged. - -## CI/CD Integration - -Check out both repositories as siblings and use an SDK matching the checked-out generator project. The following steps assume the workflow belongs to `dotnetcore/BootstrapBlazor`; pin compatible refs when building a release: - -```yaml -- uses: actions/checkout@v4 - with: - path: BootstrapBlazor -- uses: actions/checkout@v4 - with: - repository: BootstrapBlazor/BootstrapBlazor.Extensions - path: BootstrapBlazor.Extensions -- uses: actions/setup-dotnet@v4 - with: - dotnet-version: '11.0.x' - dotnet-quality: 'preview' -- name: Generate LLM Documentation - working-directory: BootstrapBlazor - run: > - dotnet run --project ../BootstrapBlazor.Extensions/tools/BootstrapBlazor.LLMsDocsGenerator - --root src/BootstrapBlazor.Server - --output src/BootstrapBlazor.Server -``` +| Option | Description | +|--------|-------------| +| `--project` | Target project file or directory. Omit to analyze the project in the current working directory. | +| `--output` | Output directory, defaulting to the current working directory. Documentation is written directly into it. | -The BB Server publish target instead restores and runs the local `llms-docs` tool pinned in BB's `dotnet-tools.json`. Its working directory is the Server project directory (`$(MSBuildThisFileDirectory)`); it uses the default `--root` and passes only `--output` with the absolute publish directory. Editing generator source does not update that package; publish a new tool version supporting these defaults and update the manifest before using the simplified target. +Without arguments, `llms-docs` analyzes the project in the current working directory and writes documentation there. It does not search parent, child or sibling directories for another project. Relative paths are resolved from the current working directory. Generation errors and explicitly empty paths return a nonzero exit code. -## Output Format +## Output -Documentation is generated in Chinese, extracted from the bilingual `` blocks in the source XML comments. Each component file (`components/.txt`) contains markdown like: +```text +\ + llms.txt + components\ + MyComponent.txt + IExampleService.txt +``` -```markdown -# BootstrapBlazor Table +`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: -Component summary from XML comments +- Parameters, types, defaults and descriptions +- Event callbacks and public methods +- Generic type parameters and base type +- Discoverable service registration methods +- Source links when the repository is recognized -### Type Parameters -- `TItem` - Generic type parameter +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. -### Parameters -| Parameter | Type | Default | Description | -|-----------|------|---------|-------------| -| Items | `List` | - | Data source | -| ShowToolbar | `bool` | false | Show toolbar | +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. -### Event Callbacks -| Event | Type | Description | -|-------|------|-------------| -| OnClick | `EventCallback` | Click handler | +## Analysis scope and limitations -### Public Methods -- `Task RefreshAsync()` - Refresh data +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`. -### Source -- Component: [src/.../Component.razor.cs](GitHub URL) -- Examples: [src/.../Samples/Components.razor](GitHub URL) -``` +This is source analysis, not a complete MSBuild or Razor compilation: -## For Library Users +- External base members and service interfaces may be missing. +- Razor inheritance declarations are synthesized; members inside `@code` blocks are not extracted. +- Explicit project `` items are supported, including aliases and static imports. +- Conditions, property expansion, imported `.props`/`.targets`, and `Using Remove` are not evaluated. -Users can reference this documentation in their own projects by creating a `llms.txt`: +The index notes the source-analysis limitations. The generator produces reference documents only; it does not create or install a skill. -```markdown -# My Project +## Validation -## Dependencies +From this repository's root, build and run integration checks with PowerShell 7: -### BootstrapBlazor -- Documentation Index: https://www.blazor.zone/llms/llms.txt -- Button: https://www.blazor.zone/llms/components/Button.txt -- Table: https://www.blazor.zone/llms/components/Table.txt -- Modal: https://www.blazor.zone/llms/components/Modal.txt +```powershell +dotnet build .\tools\BootstrapBlazor.LLMsDocsGenerator -c Release +.\tools\BootstrapBlazor.LLMsDocsGenerator\tests\Verify-SingleProject.ps1 ``` - -LLM agents can: - -1. First read `llms.txt` to discover available components -2. Then fetch specific `components/{ComponentName}.txt` for detailed API info diff --git a/tools/BootstrapBlazor.LLMsDocsGenerator/README.zh-CN.md b/tools/BootstrapBlazor.LLMsDocsGenerator/README.zh-CN.md index a3dc9bd0..b4a004e7 100644 --- a/tools/BootstrapBlazor.LLMsDocsGenerator/README.zh-CN.md +++ b/tools/BootstrapBlazor.LLMsDocsGenerator/README.zh-CN.md @@ -2,265 +2,94 @@ [English](./README.md) | 简体中文 -自动为 BootstrapBlazor 组件生成 LLM 友好文档的 .NET 工具。 - -## 目的 - -AI 编程助手(Claude Code、Cursor、GitHub Copilot)经常因为缺乏准确的组件 API 信息而生成错误的 UI 代码。本工具通过以下方式解决这个问题: - -1. **使用 Roslyn 自动生成参数表** - 从源代码提取 -2. **提供 GitHub 源码链接** - 方便深入查阅 -3. **每个组件单独成文件** - 让 Agent 只加载所需的 API - -## 架构 - -``` -┌─────────────────────────────────────────────────────────────┐ -│ BootstrapBlazor.LLMsDocsGenerator │ -├─────────────────────────────────────────────────────────────┤ -│ ComponentAnalyzer → 基于 Roslyn 的源码解析器 │ -│ MarkdownBuilder → 生成 Markdown 文档 │ -│ DocsGenerator → 协调生成流程 │ -└─────────────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────┐ -│ 默认输出目录: /wwwroot/llms/ │ -├─────────────────────────────────────────────────────────────┤ -│ llms.txt → 索引文件,包含快速入门指南 │ -│ components/ → 单独的组件文档目录 │ -│ ├── Button.txt → Button 组件 API 参考 │ -│ ├── Table.txt → Table 组件 API 参考 │ -│ ├── Select.txt → Select 组件 API 参考 │ -│ └── ... → 每个组件一个文件 │ -│ extensions/ → BootstrapBlazor.Extensions 文档 │ -│ ├── SelectCity.txt → 扩展组件 API 参考 │ -│ └── ... → 每个扩展类型一个文件 │ -└─────────────────────────────────────────────────────────────┘ -``` - -使用 `--core-only` 时,输出目录为 `` 本身。 - -### 为什么每个组件单独一个文件? - -这种设计针对 LLM 和 Code Agent 进行了优化: - -| 方面 | 按分类(旧方案) | 按组件(新方案) | -|------|-----------------|-----------------| -| **精确性** | ❌ 加载无关组件 | ✅ 只加载需要的 API | -| **Token 效率** | ❌ 浪费 token 在无关数据上 | ✅ 最小化上下文加载 | -| **缓存友好** | ❌ 需重新生成整个分类 | ✅ 只更新单个文件 | -| **RAG 检索** | ❌ 粗粒度匹配 | ✅ 细粒度匹配 | - -## 工作原理 - -### 1. 源码分析 - -`ComponentAnalyzer` 使用 Roslyn 解析 C# 源文件,扫描标记了 `[Parameter]` 特性的属性,并提取其 XML 文档注释。纯 `.cs` 文件中定义的公开组件通过 `ComponentBase` 或 `IComponent` 继承链发现。 - -### 2. 文档生成 - -`MarkdownBuilder` 生成结构化的 Markdown,包含: - -- 参数表(名称、类型、默认值、描述) -- 事件回调部分 -- 公共方法 -- GitHub 源码链接 - -### 3. 组件组织 - -组件在索引中按类别组织便于导航,但每个组件有独立的文档文件: - -| 类别 | 组件示例 | -|------|----------| -| table | Table, SelectTable, TableToolbar | -| input | BootstrapInput, Textarea, OtpInput | -| select | Select, AutoComplete, Cascader | -| button | Button, PopConfirmButton | -| dialog | Modal, Drawer, Toast | -| nav | Menu, Tab, Breadcrumb | -| card | Card, Collapse, GroupBox | -| treeview | TreeView, Tree | -| form | ValidateForm, EditorForm | -| other | 其他所有组件 | +从工程的组件与服务源码生成适合 LLM 阅读的 API 文档。单工程生成只需要目标工程,不依赖同级的其他源码仓库。 ## 环境要求 -- 与工程 `TargetFrameworks` 匹配的 SDK(当前源码构建使用 .NET 11)。 -- 本地 `BootstrapBlazor` 仓库;未使用 `--core-only` 且 `docs.json` 配置了扩展包时,还需要同级的 `BootstrapBlazor.Extensions` 仓库。生成器不会自动克隆仓库。 +- 与工具工程目标框架匹配的 SDK(当前源码构建使用 .NET 11)。 +- 目标工程的 `.csproj` 和源码文件。 ## 安装 -### 从源代码运行 - -在 `BootstrapBlazor.Extensions` 仓库根目录执行: +在本仓库根目录打包并安装工具: ```powershell -dotnet run --project tools\BootstrapBlazor.LLMsDocsGenerator --root "..\BootstrapBlazor\src\BootstrapBlazor.Server" --output "..\BootstrapBlazor\src\BootstrapBlazor.Server" +dotnet pack tools\BootstrapBlazor.LLMsDocsGenerator -c Release +dotnet tool install --global --add-source .\tools\BootstrapBlazor.LLMsDocsGenerator\bin\Release BootstrapBlazor.LLMsDocsGenerator ``` -### 作为全局工具安装 +更新或卸载: -从本地构建产物打包并安装: - -```bash -dotnet pack tools/BootstrapBlazor.LLMsDocsGenerator -c Release -dotnet tool install --global --add-source ./tools/BootstrapBlazor.LLMsDocsGenerator/bin/Release BootstrapBlazor.LLMsDocsGenerator -``` - -更新 / 卸载: - -```bash +```powershell dotnet tool update --global BootstrapBlazor.LLMsDocsGenerator dotnet tool uninstall --global BootstrapBlazor.LLMsDocsGenerator ``` -安装后,使用 `llms-docs` 命令调用。 - -## 使用方法 - -输出路径默认为当前工作目录(`.`)。默认模式下 `--root` 也默认为 `.`,在 BB 的 `src/BootstrapBlazor.Server` 目录直接执行 `llms-docs` 即可将文档生成到该工程。使用 `--core-only` 时,可在核心工程目录或仓库根目录运行,无需指定 `--root`;输出直接写入 `--output` 目录,不会清空已有内容。覆盖 `--root` 不会改变 `--output` 的默认值。 - -在 Server 工程目录运行时也支持 `dotnet llms-docs --output=bin\Release\publish\`,省略的 `--root` 使用 `.`,相对输出路径也基于当前 Server 目录解析。MSBuild 中可使用 `dotnet llms-docs --output=$(PublishDir)`(路径不含空格时)。 - -| 选项 | 必需 | 说明 | -|------|------|------| -| `--root` | 否 | Server 工程目录。指定时组件源码从 `/../BootstrapBlazor` 读取;默认模式使用 `.`,核心模式可从核心工程、仓库根目录或 Server 目录发现核心工程。 | -| `--output` | 否 | 输出目录,默认为 `.`。默认模式生成到 `/wwwroot/llms/`;`--core-only` 直接生成到 `/`。 | -| `--core-only` | 否 | 用于 BootstrapBlazor 打包,仅生成核心组件与内置服务文档。默认为 `false`,启用后不分析扩展配置与源码。 | +安装后的命令名为 `llms-docs`。 -当 `BootstrapBlazor.Extensions` 仓库与核心 `BootstrapBlazor` 仓库并列存在时,生成器也会分析扩展仓库源码。需在 `src/BootstrapBlazor.Server/docs.json` 的 `extensions` 节中配置要生成文档的扩展包和类型;这是唯一配置位置,文件不存在时生成失败。扩展文档会写入 `extensions/` 目录。 +## 单工程用法 -仅扫描 `BootstrapBlazor.Extensions.slnx` 中列出的源码工程,按工程文件名而非目录名匹配扩展包。配置中不属于解决方案的包会输出提示并跳过;解决方案引用了不存在的工程时会报错。磁盘上残留的其他目录不会参与分析。核心库中仅有 `.razor` 文件、通过 `@inherits` 指定基类的组件也支持生成文档。默认模式重新生成时会清理带有 `` 标记的过期 `.txt` 文档,保留其他文件。 - -配置了扩展包但缺少同级扩展源码仓库时,生成会失败且不改动已有文档。配置中的组件或服务类型无法解析时,也会在写入文件、清理过期文档之前报错。多个包共用的服务接口仍使用一份文档,按配置的包分别列出注册方法,使用时选择对应包的注册方式。 - -使用 `--core-only` 时,不读取 Server 的 `docs.json`、示例文件或扩展仓库及解决方案。组件索引按 `Components` 下的第一级目录分组。服务从公开、非过时的顶层类型发现:`Services` 下的接口、`Components` 下以 `Service` 或 `Provider` 结尾的接口,以及这两个目录下以 `Service` 结尾且尚未识别为组件的公开非静态类。这些是服务相关 API,不一定都由依赖注入注册;名称冲突会导致生成失败,避免覆盖文档。不生成扩展文档、扩展索引章节或链接。输出为 `/llms.txt` 与 `/components/*.txt`,索引使用适合包内引用的相对链接。不存在的输出目录会自动创建,不会清空已有内容;仅删除带生成器标记的过期文件,无标记文件与子目录会保留。 - -源码工程 `.csproj` 中显式声明的 ``(包括别名和静态导入)会应用到该工程的 C# 文件,不会在合并分析时泄漏到其他工程。 - -此工具进行源码分析,不执行完整的 MSBuild 求值:不处理条件、属性展开、导入的 `.props`/`.targets` 及 `Using Remove`。纯 Razor 支持仅合成继承声明,不编译 Razor,也不提取 `@code` 块中的成员。 - -扩展服务应配置实际用于依赖注入的注册类型。例如,两个语音包均使用 `"services": ["IRecognizerProvider", "ISynthesizerProvider"]`,而不是 Provider 实现类。 - -生成错误或显式传入空路径时会返回非零进程退出码,便于 MSBuild 和 CI 中止。 - -构建工具后,使用 PowerShell 7 执行核心模式集成检查: +在目标工程目录运行: ```powershell -dotnet build .\tools\BootstrapBlazor.LLMsDocsGenerator -c Release -.\tools\BootstrapBlazor.LLMsDocsGenerator\tests\Verify-CoreOnly.ps1 +llms-docs --output ".\artifacts\llms" ``` -### 示例 - -将 `BootstrapBlazor` 与 `BootstrapBlazor.Extensions` 仓库放在同级目录后,在 BootstrapBlazor 仓库根目录执行,两个选项都指向 Server 项目: - -```bash -llms-docs --root src/BootstrapBlazor.Server --output src/BootstrapBlazor.Server -``` - -它会从 `src/BootstrapBlazor` 读取组件,并生成: - -``` -src/BootstrapBlazor.Server/wwwroot/llms/llms.txt -src/BootstrapBlazor.Server/wwwroot/llms/components/*.txt -src/BootstrapBlazor.Server/wwwroot/llms/extensions/*.txt -``` - -索引会按扩展包分组,例如 `BootstrapBlazor.Region`;`SelectCity` 文档生成到 `extensions/SelectCity.txt`。 - -仍在 `BootstrapBlazor` 仓库根目录,通过同级仓库的源码工程执行: - -```powershell -dotnet run --project "..\BootstrapBlazor.Extensions\tools\BootstrapBlazor.LLMsDocsGenerator" --root "src\BootstrapBlazor.Server" --output "src\BootstrapBlazor.Server" -``` - -### BootstrapBlazor NuGet 打包 - -在 `BootstrapBlazor` 仓库根目录,将核心文档直接生成到 skill 的 references 目录: +也可以从其他目录指定工程: ```powershell -dotnet llms-docs --core-only --output "src\BootstrapBlazor\skills\bb-api\references" +llms-docs --project ".\src\MyComponents\MyComponents.csproj" --output ".\artifacts\llms" ``` -无需 `docs.json`。BootstrapBlazor.Server 发布时不要传 `--core-only`,以保持完整官网索引、核心与扩展文档;原有发布命令及输出路径不变。 - -## CI/CD 集成 - -将两个仓库检出到同级目录,使用与生成器工程匹配的 SDK。以下步骤假定工作流位于 `dotnetcore/BootstrapBlazor` 仓库;构建发布版本时请固定兼容的 ref: - -```yaml -- uses: actions/checkout@v4 - with: - path: BootstrapBlazor -- uses: actions/checkout@v4 - with: - repository: BootstrapBlazor/BootstrapBlazor.Extensions - path: BootstrapBlazor.Extensions -- uses: actions/setup-dotnet@v4 - with: - dotnet-version: '11.0.x' - dotnet-quality: 'preview' -- name: Generate LLM Documentation - working-directory: BootstrapBlazor - run: > - dotnet run --project ../BootstrapBlazor.Extensions/tools/BootstrapBlazor.LLMsDocsGenerator - --root src/BootstrapBlazor.Server - --output src/BootstrapBlazor.Server -``` +`--project` 也接受恰好包含一个 `.csproj` 的目录。 -BB Server 的发布 target 则还原并运行 BB 的 `dotnet-tools.json` 固定版本的本地 `llms-docs` 工具。执行目录固定为 Server 工程目录(`$(MSBuildThisFileDirectory)`),使用默认 `--root`,仅传入实际发布目录的绝对路径 `--output`。修改生成器源码不会自动更新该工具包;使用简化后的 target 前,需发布支持默认参数的新版本并更新工具清单。 +| 选项 | 说明 | +|------|------| +| `--project` | 目标工程文件或目录。省略时分析当前工作目录下的工程。 | +| `--output` | 输出目录,默认为当前工作目录,文档直接写入该目录。 | -## 输出格式 +直接运行 `llms-docs` 会分析当前工作目录下的工程,并将文档写入当前目录,不会向父目录、子目录或同级目录寻找其他工程。相对路径基于当前工作目录解析。生成错误或显式传入空路径时返回非零退出码。 -文档统一生成中文版本,从 XML 注释的双语 `` 块中提取。每个组件文件(`components/<组件名>.txt`)的 Markdown 内容形如: +## 输出 -```markdown -# BootstrapBlazor Table +```text +\ + llms.txt + components\ + MyComponent.txt + IExampleService.txt +``` -来自 XML 注释的组件描述 +`llms.txt` 使用相对链接索引工程中的组件与服务,每个类型各自生成一份 Markdown 文档,供 Agent 按需读取: -### Type Parameters -- `TItem` - 泛型类型参数 +- 参数、类型、默认值及说明 +- 事件回调与公开方法 +- 泛型参数与基类 +- 可识别的服务注册方法 +- 仓库可识别时的源码链接 -### Parameters -| Parameter | Type | Default | Description | -|-----------|------|---------|-------------| -| Items | `List` | - | 数据源 | -| ShowToolbar | `bool` | false | 显示工具栏 | +文档优先提取双语 XML 注释中的中文,无中文时使用已有文本。支持只有组件或只有服务的工程;未找到可识别的类型时生成失败。类型名称冲突可能覆盖文件时也会报错。 -### Event Callbacks -| Event | Type | Description | -|-------|------|-------------| -| OnClick | `EventCallback` | 点击处理器 | +输出目录不存在时自动创建,不会清空已有内容;仅清理带有生成器标记的过期 `.txt` 文档,保留无标记文件及子目录。 -### Public Methods -- `Task RefreshAsync()` - 刷新数据 +## 分析范围与限制 -### Source -- 组件: [src/.../Component.razor.cs](GitHub 链接) -- 示例: [src/.../Samples/Components.razor](GitHub 链接) -``` +分析器使用 Roslyn 扫描工程源码,提取 `[Parameter]` 属性、事件回调、公开方法和 XML 注释,并收录本地可解析的继承成员。服务从公开、非过时的顶层类型中发现:`Services` 目录下的接口、以 `Service` 或 `Provider` 结尾的接口,以及以 `Service` 或 `Provider` 结尾的非静态类。 -## 库用户使用指南 +这是源码分析,不是完整的 MSBuild 或 Razor 编译: -用户可以在自己的项目中创建 `llms.txt` 来引用本文档: +- 外部基类成员与服务接口可能未收录。 +- Razor 仅合成继承声明,不提取 `@code` 中的成员。 +- 支持工程中显式声明的 ``,包括别名和静态导入。 +- 不处理条件、属性展开、导入的 `.props`/`.targets` 及 `Using Remove`。 -```markdown -# 我的项目 +索引中会提示源码分析的限制。生成器只产出参考文档,不创建或安装 skill。 -## 依赖 +## 验证 -### BootstrapBlazor -- 文档索引: https://www.blazor.zone/llms/llms.txt -- Button: https://www.blazor.zone/llms/components/Button.txt -- Table: https://www.blazor.zone/llms/components/Table.txt -- Modal: https://www.blazor.zone/llms/components/Modal.txt -``` +在本仓库根目录构建,并使用 PowerShell 7 执行集成检查: -LLM 代理可以: - -1. 先读取 `llms.txt` 了解有哪些组件 -2. 然后获取 `components/{组件名}.txt` 获取详细 API 信息 +```powershell +dotnet build .\tools\BootstrapBlazor.LLMsDocsGenerator -c Release +.\tools\BootstrapBlazor.LLMsDocsGenerator\tests\Verify-SingleProject.ps1 ``` From 8fd5d586c0f5ba9991eca39a9a23e910876eb3bd Mon Sep 17 00:00:00 2001 From: Argo Zhang Date: Tue, 17 Nov 2026 08:38:18 +0800 Subject: [PATCH 2/2] chore: bump version 11.0.3 --- .../BootstrapBlazor.LLMsDocsGenerator.csproj | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tools/BootstrapBlazor.LLMsDocsGenerator/BootstrapBlazor.LLMsDocsGenerator.csproj b/tools/BootstrapBlazor.LLMsDocsGenerator/BootstrapBlazor.LLMsDocsGenerator.csproj index fe2f6316..b3e25d95 100644 --- a/tools/BootstrapBlazor.LLMsDocsGenerator/BootstrapBlazor.LLMsDocsGenerator.csproj +++ b/tools/BootstrapBlazor.LLMsDocsGenerator/BootstrapBlazor.LLMsDocsGenerator.csproj @@ -1,7 +1,7 @@  - 11.0.2 + 11.0.3 Exe false @@ -10,6 +10,8 @@ BootstrapBlazor LLMs docs Generator Generates LLM-friendly API documentation for BootstrapBlazor components from source code. BootstrapBlazor.LLMsDocsGenerator + Apache-2.0 + README.md true llms-docs