< Summary

Information
Class: NexusLabs.Needlr.Generators.Export.CollectedDiagnostic
Assembly: NexusLabs.Needlr.Generators
File(s): /home/runner/work/needlr/needlr/src/NexusLabs.Needlr.Generators/Export/GraphExporter.cs
Line coverage
100%
Covered lines: 6
Uncovered lines: 0
Coverable lines: 6
Total lines: 629
Line coverage: 100%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
get_Id()100%11100%
get_Severity()100%11100%
get_Message()100%11100%
get_FilePath()100%11100%
get_Line()100%11100%
get_RelatedServices()100%11100%

File(s)

/home/runner/work/needlr/needlr/src/NexusLabs.Needlr.Generators/Export/GraphExporter.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Text;
 5using NexusLabs.Needlr.Generators.Models;
 6
 7namespace NexusLabs.Needlr.Generators.Export;
 8
 9/// <summary>
 10/// Generates the Needlr dependency graph JSON for IDE tooling.
 11/// </summary>
 12internal static class GraphExporter
 13{
 14    /// <summary>
 15    /// Placeholder emitted in place of a wall-clock timestamp so generated source stays
 16    /// byte-identical across builds. It is a schema-valid RFC 3339 value, so the embedded
 17    /// JSON still satisfies <c>needlr-graph-v1.schema.json</c>. The generated
 18    /// <c>WriteGraphToFile</c> substitutes the real UTC time when the graph is written.
 19    /// </summary>
 20    internal const string GeneratedAtSentinel = "0001-01-01T00:00:00.0000000+00:00";
 21
 22    /// <summary>
 23    /// Generates the needlr-graph.json content from the discovery result.
 24    /// </summary>
 25    public static string GenerateGraphJson(
 26        DiscoveryResult discoveryResult,
 27        string assemblyName,
 28        string? projectPath,
 29        IReadOnlyList<CollectedDiagnostic>? diagnostics = null,
 30        IReadOnlyDictionary<string, IReadOnlyList<DiscoveredType>>? referencedAssemblyTypes = null)
 31    {
 32        var graph = BuildGraph(discoveryResult, assemblyName, projectPath, diagnostics, referencedAssemblyTypes);
 33        return SerializeToJson(graph);
 34    }
 35
 36    private static NeedlrGraph BuildGraph(
 37        DiscoveryResult discoveryResult,
 38        string assemblyName,
 39        string? projectPath,
 40        IReadOnlyList<CollectedDiagnostic>? diagnostics,
 41        IReadOnlyDictionary<string, IReadOnlyList<DiscoveredType>>? referencedAssemblyTypes)
 42    {
 43        var graph = new NeedlrGraph
 44        {
 45            SchemaVersion = "1.0",
 46            GeneratedAt = GeneratedAtSentinel,
 47            ProjectPath = projectPath,
 48            AssemblyName = assemblyName
 49        };
 50
 51        // Build type lookup for resolving dependencies (include referenced assembly types)
 52        var typeLookup = BuildTypeLookup(discoveryResult, referencedAssemblyTypes);
 53
 54        // Map injectable types from current assembly to graph services
 55        foreach (var type in discoveryResult.InjectableTypes)
 56        {
 57            var service = MapToGraphService(type, assemblyName, typeLookup, discoveryResult);
 58            graph.Services.Add(service);
 59        }
 60
 61        // Add types from referenced assemblies with [GenerateTypeRegistry]
 62        if (referencedAssemblyTypes != null)
 63        {
 64            foreach (var kvp in referencedAssemblyTypes)
 65            {
 66                var refAssemblyName = kvp.Key;
 67                var types = kvp.Value;
 68                foreach (var type in types)
 69                {
 70                    var service = MapToGraphService(type, refAssemblyName, typeLookup, discoveryResult);
 71                    graph.Services.Add(service);
 72                }
 73            }
 74        }
 75
 76        // Add diagnostics if provided
 77        if (diagnostics != null)
 78        {
 79            foreach (var diag in diagnostics)
 80            {
 81                graph.Diagnostics.Add(new GraphDiagnostic
 82                {
 83                    Id = diag.Id,
 84                    Severity = diag.Severity,
 85                    Message = diag.Message,
 86                    Location = diag.FilePath != null ? new GraphLocation
 87                    {
 88                        FilePath = diag.FilePath,
 89                        Line = diag.Line,
 90                        Column = 0
 91                    } : null,
 92                    RelatedServices = diag.RelatedServices?.ToList() ?? new List<string>()
 93                });
 94            }
 95        }
 96
 97        // Compute statistics (include referenced assembly types in count)
 98        graph.Statistics = ComputeStatistics(discoveryResult, referencedAssemblyTypes);
 99
 100        return graph;
 101    }
 102
 103    private static Dictionary<string, DiscoveredType> BuildTypeLookup(
 104        DiscoveryResult discoveryResult,
 105        IReadOnlyDictionary<string, IReadOnlyList<DiscoveredType>>? referencedAssemblyTypes)
 106    {
 107        var lookup = new Dictionary<string, DiscoveredType>();
 108
 109        // Add types from current assembly
 110        foreach (var type in discoveryResult.InjectableTypes)
 111        {
 112            lookup[type.TypeName] = type;
 113            foreach (var iface in type.InterfaceNames)
 114            {
 115                if (!lookup.ContainsKey(iface))
 116                {
 117                    lookup[iface] = type;
 118                }
 119            }
 120        }
 121
 122        // Add types from referenced assemblies for dependency resolution
 123        if (referencedAssemblyTypes != null)
 124        {
 125            foreach (var kvp in referencedAssemblyTypes)
 126            {
 127                foreach (var type in kvp.Value)
 128                {
 129                    if (!lookup.ContainsKey(type.TypeName))
 130                    {
 131                        lookup[type.TypeName] = type;
 132                    }
 133                    foreach (var iface in type.InterfaceNames)
 134                    {
 135                        if (!lookup.ContainsKey(iface))
 136                        {
 137                            lookup[iface] = type;
 138                        }
 139                    }
 140                }
 141            }
 142        }
 143
 144        return lookup;
 145    }
 146
 147    private static GraphService MapToGraphService(
 148        DiscoveredType type,
 149        string assemblyName,
 150        Dictionary<string, DiscoveredType> typeLookup,
 151        DiscoveryResult discoveryResult)
 152    {
 153        var service = new GraphService
 154        {
 155            Id = type.TypeName,
 156            TypeName = GetSimpleTypeName(type.TypeName),
 157            FullTypeName = type.TypeName,
 158            AssemblyName = assemblyName,
 159            Lifetime = type.Lifetime.ToString(),
 160            Location = type.SourceFilePath != null ? new GraphLocation
 161            {
 162                FilePath = type.SourceFilePath,
 163                Line = type.SourceLine,
 164                Column = 0
 165            } : null,
 166            ServiceKeys = type.ServiceKeys.ToList(),
 167            Metadata = new GraphServiceMetadata
 168            {
 169                IsDisposable = type.IsDisposable,
 170                HasFactory = discoveryResult.Factories.Any(f => f.TypeName == type.TypeName),
 171                HasOptions = discoveryResult.Options.Any(o => o.TypeName == type.TypeName),
 172                IsHostedService = discoveryResult.HostedServices.Any(h => h.TypeName == type.TypeName),
 173                IsPlugin = discoveryResult.PluginTypes.Any(p => p.TypeName == type.TypeName)
 174            }
 175        };
 176
 177        // Map interfaces with locations
 178        foreach (var ifaceInfo in type.InterfaceInfos)
 179        {
 180            service.Interfaces.Add(new GraphInterface
 181            {
 182                Name = GetSimpleTypeName(ifaceInfo.FullName),
 183                FullName = ifaceInfo.FullName,
 184                Location = ifaceInfo.HasLocation ? new GraphLocation
 185                {
 186                    FilePath = ifaceInfo.SourceFilePath!,
 187                    Line = ifaceInfo.SourceLine,
 188                    Column = 0
 189                } : null
 190            });
 191        }
 192        // Fall back to InterfaceNames if no InterfaceInfos (for backwards compat)
 193        if (type.InterfaceInfos.Length == 0)
 194        {
 195            foreach (var iface in type.InterfaceNames)
 196            {
 197                service.Interfaces.Add(new GraphInterface
 198                {
 199                    Name = GetSimpleTypeName(iface),
 200                    FullName = iface
 201                });
 202            }
 203        }
 204
 205        // Map dependencies from constructor parameters
 206        foreach (var param in type.ConstructorParameters)
 207        {
 208            var dependency = new GraphDependency
 209            {
 210                ParameterName = param.ParameterName ?? string.Empty,
 211                TypeName = GetSimpleTypeName(param.TypeName),
 212                FullTypeName = param.TypeName,
 213                IsKeyed = param.IsKeyed,
 214                ServiceKey = param.ServiceKey
 215            };
 216
 217            // Try to resolve the dependency
 218            if (typeLookup.TryGetValue(param.TypeName, out var resolved))
 219            {
 220                dependency.ResolvedTo = resolved.TypeName;
 221                dependency.ResolvedLifetime = resolved.Lifetime.ToString();
 222            }
 223
 224            service.Dependencies.Add(dependency);
 225        }
 226
 227        // Map decorators
 228        var decorators = discoveryResult.Decorators
 229            .Where(d => type.InterfaceNames.Contains(d.ServiceTypeName))
 230            .OrderBy(d => d.Order);
 231
 232        foreach (var decorator in decorators)
 233        {
 234            service.Decorators.Add(new GraphDecorator
 235            {
 236                TypeName = decorator.DecoratorTypeName,
 237                Order = decorator.Order
 238            });
 239        }
 240
 241        // Map interceptors
 242        var intercepted = discoveryResult.InterceptedServices
 243            .FirstOrDefault(i => i.TypeName == type.TypeName);
 244
 245        if (intercepted.TypeName != null)
 246        {
 247            service.Interceptors = intercepted.AllInterceptorTypeNames.ToList();
 248        }
 249
 250        // Collect attributes
 251        service.Attributes.Add(type.Lifetime.ToString());
 252        if (type.IsKeyed)
 253        {
 254            service.Attributes.Add("Keyed");
 255        }
 256
 257        return service;
 258    }
 259
 260    private static GraphStatistics ComputeStatistics(
 261        DiscoveryResult discoveryResult,
 262        IReadOnlyDictionary<string, IReadOnlyList<DiscoveredType>>? referencedAssemblyTypes)
 263    {
 264        // Get all types for statistics - current assembly + referenced assemblies
 265        var allTypes = new List<DiscoveredType>(discoveryResult.InjectableTypes);
 266        if (referencedAssemblyTypes != null)
 267        {
 268            foreach (var kvp in referencedAssemblyTypes)
 269            {
 270                allTypes.AddRange(kvp.Value);
 271            }
 272        }
 273
 274        return new GraphStatistics
 275        {
 276            TotalServices = allTypes.Count,
 277            Singletons = allTypes.Count(t => t.Lifetime == GeneratorLifetime.Singleton),
 278            Scoped = allTypes.Count(t => t.Lifetime == GeneratorLifetime.Scoped),
 279            Transient = allTypes.Count(t => t.Lifetime == GeneratorLifetime.Transient),
 280            Decorators = discoveryResult.Decorators.Count,
 281            Interceptors = discoveryResult.InterceptedServices.Count,
 282            Factories = discoveryResult.Factories.Count,
 283            Options = discoveryResult.Options.Count,
 284            HostedServices = discoveryResult.HostedServices.Count,
 285            Plugins = discoveryResult.PluginTypes.Count
 286        };
 287    }
 288
 289    private static string GetSimpleTypeName(string fullTypeName)
 290    {
 291        // Remove global:: prefix
 292        var name = fullTypeName;
 293        if (name.StartsWith("global::"))
 294        {
 295            name = name.Substring(8);
 296        }
 297
 298        // Handle generic types like Lazy<T> or IReadOnlyList<Assembly>
 299        // We want to preserve the generic structure but simplify inner types
 300        var genericStart = name.IndexOf('<');
 301        if (genericStart >= 0)
 302        {
 303            // Get the outer type name (before generic params)
 304            var outerPart = name.Substring(0, genericStart);
 305            var lastDot = outerPart.LastIndexOf('.');
 306            var simpleOuter = lastDot >= 0 ? outerPart.Substring(lastDot + 1) : outerPart;
 307
 308            // Get the generic parameters and simplify them recursively
 309            var genericEnd = name.LastIndexOf('>');
 310            if (genericEnd > genericStart)
 311            {
 312                var genericParams = name.Substring(genericStart + 1, genericEnd - genericStart - 1);
 313                // Simplify each generic parameter (split by comma, handle nested generics)
 314                var simplifiedParams = SimplifyGenericParameters(genericParams);
 315                return $"{simpleOuter}<{simplifiedParams}>";
 316            }
 317
 318            return simpleOuter;
 319        }
 320
 321        // Get just the type name (after last dot)
 322        var idx = name.LastIndexOf('.');
 323        return idx >= 0 ? name.Substring(idx + 1) : name;
 324    }
 325
 326    private static string SimplifyGenericParameters(string genericParams)
 327    {
 328        // Handle nested generics by tracking depth
 329        var result = new StringBuilder();
 330        var depth = 0;
 331        var currentParam = new StringBuilder();
 332
 333        foreach (var c in genericParams)
 334        {
 335            if (c == '<')
 336            {
 337                depth++;
 338                currentParam.Append(c);
 339            }
 340            else if (c == '>')
 341            {
 342                depth--;
 343                currentParam.Append(c);
 344            }
 345            else if (c == ',' && depth == 0)
 346            {
 347                // End of parameter at top level
 348                if (result.Length > 0)
 349                {
 350                    result.Append(", ");
 351                }
 352                result.Append(GetSimpleTypeName(currentParam.ToString().Trim()));
 353                currentParam.Clear();
 354            }
 355            else
 356            {
 357                currentParam.Append(c);
 358            }
 359        }
 360
 361        // Add last parameter
 362        if (currentParam.Length > 0)
 363        {
 364            if (result.Length > 0)
 365            {
 366                result.Append(", ");
 367            }
 368            result.Append(GetSimpleTypeName(currentParam.ToString().Trim()));
 369        }
 370
 371        return result.ToString();
 372    }
 373
 374    /// <summary>
 375    /// Serializes the graph to JSON without using System.Text.Json (not available in all targets).
 376    /// Uses simple string building for source generator compatibility.
 377    /// </summary>
 378    private static string SerializeToJson(NeedlrGraph graph)
 379    {
 380        var sb = new StringBuilder();
 381        sb.AppendLine("{");
 382        sb.AppendLine($"  \"schemaVersion\": \"{Escape(graph.SchemaVersion)}\",");
 383        sb.AppendLine($"  \"generatedAt\": \"{Escape(graph.GeneratedAt)}\",");
 384        sb.AppendLine($"  \"projectPath\": {NullableString(graph.ProjectPath)},");
 385        sb.AppendLine($"  \"assemblyName\": {NullableString(graph.AssemblyName)},");
 386
 387        // Services array
 388        sb.AppendLine("  \"services\": [");
 389        for (int i = 0; i < graph.Services.Count; i++)
 390        {
 391            SerializeService(sb, graph.Services[i], i == graph.Services.Count - 1);
 392        }
 393        sb.AppendLine("  ],");
 394
 395        // Diagnostics array
 396        sb.AppendLine("  \"diagnostics\": [");
 397        for (int i = 0; i < graph.Diagnostics.Count; i++)
 398        {
 399            SerializeDiagnostic(sb, graph.Diagnostics[i], i == graph.Diagnostics.Count - 1);
 400        }
 401        sb.AppendLine("  ],");
 402
 403        // Statistics object
 404        sb.AppendLine("  \"statistics\": {");
 405        sb.AppendLine($"    \"totalServices\": {GeneratorHelpers.Literal(graph.Statistics.TotalServices)},");
 406        sb.AppendLine($"    \"singletons\": {GeneratorHelpers.Literal(graph.Statistics.Singletons)},");
 407        sb.AppendLine($"    \"scoped\": {GeneratorHelpers.Literal(graph.Statistics.Scoped)},");
 408        sb.AppendLine($"    \"transient\": {GeneratorHelpers.Literal(graph.Statistics.Transient)},");
 409        sb.AppendLine($"    \"decorators\": {GeneratorHelpers.Literal(graph.Statistics.Decorators)},");
 410        sb.AppendLine($"    \"interceptors\": {GeneratorHelpers.Literal(graph.Statistics.Interceptors)},");
 411        sb.AppendLine($"    \"factories\": {GeneratorHelpers.Literal(graph.Statistics.Factories)},");
 412        sb.AppendLine($"    \"options\": {GeneratorHelpers.Literal(graph.Statistics.Options)},");
 413        sb.AppendLine($"    \"hostedServices\": {GeneratorHelpers.Literal(graph.Statistics.HostedServices)},");
 414        sb.AppendLine($"    \"plugins\": {GeneratorHelpers.Literal(graph.Statistics.Plugins)}");
 415        sb.AppendLine("  }");
 416
 417        sb.AppendLine("}");
 418        return sb.ToString();
 419    }
 420
 421    private static void SerializeService(StringBuilder sb, GraphService service, bool isLast)
 422    {
 423        sb.AppendLine("    {");
 424        sb.AppendLine($"      \"id\": \"{Escape(service.Id)}\",");
 425        sb.AppendLine($"      \"typeName\": \"{Escape(service.TypeName)}\",");
 426        sb.AppendLine($"      \"fullTypeName\": \"{Escape(service.FullTypeName)}\",");
 427        sb.AppendLine($"      \"assemblyName\": {NullableString(service.AssemblyName)},");
 428
 429        // Interfaces
 430        sb.AppendLine("      \"interfaces\": [");
 431        for (int i = 0; i < service.Interfaces.Count; i++)
 432        {
 433            var iface = service.Interfaces[i];
 434            var comma = i < service.Interfaces.Count - 1 ? "," : "";
 435            sb.AppendLine("        {");
 436            sb.AppendLine($"          \"name\": \"{Escape(iface.Name)}\",");
 437            sb.AppendLine($"          \"fullName\": \"{Escape(iface.FullName)}\",");
 438            if (iface.Location != null)
 439            {
 440                sb.AppendLine("          \"location\": {");
 441                sb.AppendLine($"            \"filePath\": {NullableString(iface.Location.FilePath)},");
 442                sb.AppendLine($"            \"line\": {GeneratorHelpers.Literal(iface.Location.Line)},");
 443                sb.AppendLine($"            \"column\": {GeneratorHelpers.Literal(iface.Location.Column)}");
 444                sb.AppendLine("          }");
 445            }
 446            else
 447            {
 448                sb.AppendLine("          \"location\": null");
 449            }
 450            sb.AppendLine($"        }}{comma}");
 451        }
 452        sb.AppendLine("      ],");
 453
 454        sb.AppendLine($"      \"lifetime\": \"{Escape(service.Lifetime)}\",");
 455
 456        // Location
 457        if (service.Location != null)
 458        {
 459            sb.AppendLine("      \"location\": {");
 460            sb.AppendLine($"        \"filePath\": {NullableString(service.Location.FilePath)},");
 461            sb.AppendLine($"        \"line\": {GeneratorHelpers.Literal(service.Location.Line)},");
 462            sb.AppendLine($"        \"column\": {GeneratorHelpers.Literal(service.Location.Column)}");
 463            sb.AppendLine("      },");
 464        }
 465        else
 466        {
 467            sb.AppendLine("      \"location\": null,");
 468        }
 469
 470        // Dependencies
 471        sb.AppendLine("      \"dependencies\": [");
 472        for (int i = 0; i < service.Dependencies.Count; i++)
 473        {
 474            var dep = service.Dependencies[i];
 475            var comma = i < service.Dependencies.Count - 1 ? "," : "";
 476            sb.AppendLine("        {");
 477            sb.AppendLine($"          \"parameterName\": \"{Escape(dep.ParameterName)}\",");
 478            sb.AppendLine($"          \"typeName\": \"{Escape(dep.TypeName)}\",");
 479            sb.AppendLine($"          \"fullTypeName\": \"{Escape(dep.FullTypeName)}\",");
 480            sb.AppendLine($"          \"resolvedTo\": {NullableString(dep.ResolvedTo)},");
 481            sb.AppendLine($"          \"resolvedLifetime\": {NullableString(dep.ResolvedLifetime)},");
 482            sb.AppendLine($"          \"isKeyed\": {dep.IsKeyed.ToString().ToLowerInvariant()},");
 483            sb.AppendLine($"          \"serviceKey\": {NullableString(dep.ServiceKey)}");
 484            sb.AppendLine($"        }}{comma}");
 485        }
 486        sb.AppendLine("      ],");
 487
 488        // Decorators
 489        sb.AppendLine("      \"decorators\": [");
 490        for (int i = 0; i < service.Decorators.Count; i++)
 491        {
 492            var dec = service.Decorators[i];
 493            var comma = i < service.Decorators.Count - 1 ? "," : "";
 494            sb.AppendLine($"        {{ \"typeName\": \"{Escape(dec.TypeName)}\", \"order\": {GeneratorHelpers.Literal(de
 495        }
 496        sb.AppendLine("      ],");
 497
 498        // Interceptors
 499        sb.Append("      \"interceptors\": [");
 500        sb.Append(string.Join(", ", service.Interceptors.Select(i => $"\"{Escape(i)}\"")));
 501        sb.AppendLine("],");
 502
 503        // Attributes
 504        sb.Append("      \"attributes\": [");
 505        sb.Append(string.Join(", ", service.Attributes.Select(a => $"\"{Escape(a)}\"")));
 506        sb.AppendLine("],");
 507
 508        // Service keys
 509        sb.Append("      \"serviceKeys\": [");
 510        sb.Append(string.Join(", ", service.ServiceKeys.Select(k => $"\"{Escape(k)}\"")));
 511        sb.AppendLine("],");
 512
 513        // Metadata
 514        sb.AppendLine("      \"metadata\": {");
 515        sb.AppendLine($"        \"hasFactory\": {service.Metadata.HasFactory.ToString().ToLowerInvariant()},");
 516        sb.AppendLine($"        \"hasOptions\": {service.Metadata.HasOptions.ToString().ToLowerInvariant()},");
 517        sb.AppendLine($"        \"isHostedService\": {service.Metadata.IsHostedService.ToString().ToLowerInvariant()},")
 518        sb.AppendLine($"        \"isDisposable\": {service.Metadata.IsDisposable.ToString().ToLowerInvariant()},");
 519        sb.AppendLine($"        \"isPlugin\": {service.Metadata.IsPlugin.ToString().ToLowerInvariant()}");
 520        sb.AppendLine("      }");
 521
 522        sb.AppendLine(isLast ? "    }" : "    },");
 523    }
 524
 525    private static void SerializeDiagnostic(StringBuilder sb, GraphDiagnostic diagnostic, bool isLast)
 526    {
 527        sb.AppendLine("    {");
 528        sb.AppendLine($"      \"id\": \"{Escape(diagnostic.Id)}\",");
 529        sb.AppendLine($"      \"severity\": \"{Escape(diagnostic.Severity)}\",");
 530        sb.AppendLine($"      \"message\": \"{Escape(diagnostic.Message)}\",");
 531
 532        if (diagnostic.Location != null)
 533        {
 534            sb.AppendLine("      \"location\": {");
 535            sb.AppendLine($"        \"filePath\": {NullableString(diagnostic.Location.FilePath)},");
 536            sb.AppendLine($"        \"line\": {GeneratorHelpers.Literal(diagnostic.Location.Line)},");
 537            sb.AppendLine($"        \"column\": {GeneratorHelpers.Literal(diagnostic.Location.Column)}");
 538            sb.AppendLine("      },");
 539        }
 540        else
 541        {
 542            sb.AppendLine("      \"location\": null,");
 543        }
 544
 545        sb.Append("      \"relatedServices\": [");
 546        sb.Append(string.Join(", ", diagnostic.RelatedServices.Select(s => $"\"{Escape(s)}\"")));
 547        sb.AppendLine("]");
 548
 549        sb.AppendLine(isLast ? "    }" : "    },");
 550    }
 551
 552    private static string Escape(string value)
 553    {
 554        if (string.IsNullOrEmpty(value))
 555            return value;
 556
 557        return value
 558            .Replace("\\", "\\\\")
 559            .Replace("\"", "\\\"")
 560            .Replace("\n", "\\n")
 561            .Replace("\r", "\\r")
 562            .Replace("\t", "\\t");
 563    }
 564
 565    private static string NullableString(string? value)
 566    {
 567        return value == null ? "null" : $"\"{Escape(value)}\"";
 568    }
 569
 570    /// <summary>
 571    /// Generates the NeedlrGraph.g.cs source file that embeds the graph JSON
 572    /// in a generated class for IDE tooling.
 573    /// </summary>
 574    internal static string GenerateGraphExportSource(string graphJson, string assemblyName, BreadcrumbWriter breadcrumbs
 575    {
 576        var sb = new StringBuilder();
 577
 578        breadcrumbs.WriteFileHeader(sb, assemblyName, "Needlr IDE Graph Export");
 579
 580        sb.AppendLine("using System;");
 581        sb.AppendLine("using System.IO;");
 582        sb.AppendLine();
 583        sb.AppendLine($"namespace {assemblyName}.Generated");
 584        sb.AppendLine("{");
 585        sb.AppendLine("    /// <summary>");
 586        sb.AppendLine("    /// Provides the Needlr dependency graph for IDE tooling.");
 587        sb.AppendLine("    /// </summary>");
 588        sb.AppendLine("    internal static class NeedlrGraphExport");
 589        sb.AppendLine("    {");
 590        sb.AppendLine("        /// <summary>");
 591        sb.AppendLine("        /// Gets the dependency graph JSON.");
 592        sb.AppendLine("        /// </summary>");
 593        sb.AppendLine("        public static string GraphJson => GraphJsonContent;");
 594        sb.AppendLine();
 595        sb.AppendLine("        private const string GraphJsonContent = @\"");
 596
 597        // Escape the JSON for C# verbatim string (double quotes only)
 598        var escapedJson = graphJson.Replace("\"", "\"\"");
 599        sb.Append(escapedJson);
 600
 601        sb.AppendLine("\";");
 602        sb.AppendLine();
 603        sb.AppendLine("        /// <summary>");
 604        sb.AppendLine("        /// Writes the graph to the specified path, stamping the current UTC time.");
 605        sb.AppendLine("        /// </summary>");
 606        sb.AppendLine("        public static void WriteGraphToFile(string path)");
 607        sb.AppendLine("        {");
 608        sb.AppendLine($"            var stamped = GraphJson.Replace(\"{GeneratedAtSentinel}\", DateTime.UtcNow.ToString(
 609        sb.AppendLine("            File.WriteAllText(path, stamped);");
 610        sb.AppendLine("        }");
 611        sb.AppendLine("    }");
 612        sb.AppendLine("}");
 613
 614        return sb.ToString();
 615    }
 616}
 617
 618/// <summary>
 619/// Represents a diagnostic collected during generation for inclusion in the graph.
 620/// </summary>
 621internal sealed class CollectedDiagnostic
 622{
 18623    public string Id { get; set; } = string.Empty;
 18624    public string Severity { get; set; } = string.Empty;
 18625    public string Message { get; set; } = string.Empty;
 16626    public string? FilePath { get; set; }
 10627    public int Line { get; set; }
 10628    public IReadOnlyList<string>? RelatedServices { get; set; }
 629}