using System; using System.Linq; using Kiota.Builder.CodeDOM; namespace Kiota.Builder.Writers.TypeScript; public class CodeFileDeclarationWriter : BaseElementWriter { private readonly CodeUsingWriter _codeUsingWriter; public CodeFileDeclarationWriter(TypeScriptConventionService conventionService, string clientNamespaceName) : base(conventionService) { _codeUsingWriter = new(clientNamespaceName); } public override void WriteCodeElement(CodeFileDeclaration codeElement, LanguageWriter writer) { ArgumentNullException.ThrowIfNull(codeElement); ArgumentNullException.ThrowIfNull(writer); if (codeElement.Parent is CodeFile cf && cf.Parent is CodeNamespace ns) { var usings = cf.GetChildElements().SelectMany(static x => { return x switch { CodeFunction f => f.StartBlock.Usings, CodeInterface ci => ci.Usings, CodeClass cc => cc.Usings, CodeConstant c => c.StartBlock.Usings, _ => Enumerable.Empty() }; } ); conventions.WriteAutoGeneratedStart(writer); // remove duplicate using, keep a single using for each internal type in the same namespace var enumeratedUsing = usings.ToArray(); var filteredUsing = enumeratedUsing.Where(static x => x.IsExternal) .Union(enumeratedUsing .Where(static x => x is { IsExternal: false, Declaration.TypeDefinition: not null }) .GroupBy(static x => $"{x.Declaration!.TypeDefinition!.GetImmediateParentOfType().Name}.{x.Declaration?.Name.ToLowerInvariant()}") .Select(static x => x.OrderByDescending(static x => x.Alias, StringComparer.OrdinalIgnoreCase).ThenBy(static x => x.Parent?.Name, StringComparer.OrdinalIgnoreCase).First())); _codeUsingWriter.WriteCodeElement(filteredUsing, ns, writer); } } }