Something went wrong. Try again.
.NET ATProtocol Library - Built for Source Gen
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586// <auto-generated />#nullable enable
using System;using System.Collections.Generic;using CarpaNet.Models;using CarpaNet.Utilities;
namespace CarpaNet;
/// <summary>/// Represents the kind of type a Lexicon definition represents./// </summary>public enum LexiconTypeKind{ /// <summary>Unknown or unresolved type.</summary> Unknown, /// <summary>A primitive string type (may have format, knownValues, enum).</summary> String, /// <summary>A primitive boolean type.</summary> Boolean, /// <summary>A primitive integer type.</summary> Integer, /// <summary>A bytes type.</summary> Bytes, /// <summary>A CID link type.</summary> CidLink, /// <summary>A blob type.</summary> Blob, /// <summary>An object type (generates a class).</summary> Object, /// <summary>A record type (generates a class with $type).</summary> Record, /// <summary>A query type (HTTP GET).</summary> Query, /// <summary>A procedure type (HTTP POST).</summary> Procedure, /// <summary>A subscription type (WebSocket).</summary> Subscription, /// <summary>A union type (generates an interface).</summary> Union, /// <summary>A token type (symbolic constant).</summary> Token, /// <summary>An array type.</summary> Array, /// <summary>A ref type (reference to another definition).</summary> Ref, /// <summary>An unknown/any type.</summary> Any, /// <summary>Params type (query parameters).</summary> Params,}
/// <summary>/// Information about a registered type./// </summary>public sealed class TypeInfo{ /// <summary>The full reference string (NSID#defName or NSID for main).</summary> public string FullRef { get; set; } = string.Empty;
/// <summary>The NSID of the lexicon containing this type.</summary> public string Nsid { get; set; } = string.Empty;
/// <summary>The definition name within the lexicon.</summary> public string DefName { get; set; } = string.Empty;
/// <summary>The kind of type this represents.</summary> public LexiconTypeKind Kind { get; set; }
/// <summary>The C# namespace for this type.</summary> public string CSharpNamespace { get; set; } = string.Empty;
/// <summary>The C# type name (class/interface name).</summary> public string CSharpTypeName { get; set; } = string.Empty;
/// <summary>The fully qualified C# type name.</summary> public string FullCSharpTypeName => $"{CSharpNamespace}.{CSharpTypeName}";
/// <summary>The original Lexicon definition.</summary> public LexiconDefinition? Definition { get; set; }
/// <summary>For union types, the list of variant refs.</summary> public List<string>? UnionRefs { get; set; }
/// <summary>Whether this type should generate a class (vs being mapped to a primitive).</summary> public bool GeneratesClass => Kind == LexiconTypeKind.Object || Kind == LexiconTypeKind.Record || Kind == LexiconTypeKind.Query || Kind == LexiconTypeKind.Procedure || Kind == LexiconTypeKind.Subscription;
/// <summary>Whether this type should generate an interface (union).</summary> public bool GeneratesInterface => Kind == LexiconTypeKind.Union;
/// <summary>Whether this type maps to a primitive C# type.</summary> public bool IsPrimitive => Kind == LexiconTypeKind.String || Kind == LexiconTypeKind.Boolean || Kind == LexiconTypeKind.Integer || Kind == LexiconTypeKind.Bytes || Kind == LexiconTypeKind.CidLink || Kind == LexiconTypeKind.Blob || Kind == LexiconTypeKind.Token || Kind == LexiconTypeKind.Any;}
/// <summary>/// Registry that tracks all Lexicon type definitions and their resolved C# types./// </summary>public sealed class TypeRegistry{ private readonly Dictionary<string, TypeInfo> _types = new(StringComparer.Ordinal); private readonly HashSet<string> _unresolvedRefs = new(StringComparer.Ordinal); private readonly string? _rootNamespace;
public TypeRegistry(string? rootNamespace = null) { _rootNamespace = rootNamespace; }
/// <summary> /// Registers all definitions from a lexicon document. /// </summary> public void RegisterDocument(LexiconDocument document) { var nsid = document.Id; var ns = NsidHelper.ToNamespace(nsid, _rootNamespace);
foreach (var def in document.Defs) { var defName = def.Key; var defValue = def.Value;
// Build the full reference var fullRef = defName == "main" ? nsid : $"{nsid}#{defName}";
// Determine the C# type name (escaped for C# keywords) // For non-main definitions, prefix with the main type name to avoid collisions var mainTypeName = NsidHelper.ToTypeName(nsid); var rawTypeName = defName == "main" ? mainTypeName : mainTypeName + NsidHelper.ToPascalCase(defName); var csharpTypeName = NsidHelper.EscapeIdentifier(rawTypeName);
var typeInfo = new TypeInfo { FullRef = fullRef, Nsid = nsid, DefName = defName, CSharpNamespace = ns, CSharpTypeName = csharpTypeName, Definition = defValue, Kind = GetTypeKind(defValue), };
// For unions, track the variant refs if (typeInfo.Kind == LexiconTypeKind.Union && defValue.Refs != null) { typeInfo.UnionRefs = new List<string>(defValue.Refs); }
_types[fullRef] = typeInfo;
// For main definitions, register under multiple keys for lookup flexibility if (defName == "main") { // Also register without fragment (just nsid) if (!_types.ContainsKey(nsid)) { _types[nsid] = typeInfo; } // Also register with explicit #main suffix var mainRef = $"{nsid}#main"; if (!_types.ContainsKey(mainRef)) { _types[mainRef] = typeInfo; } } } }
/// <summary> /// Gets the type kind for a definition. /// </summary> private static LexiconTypeKind GetTypeKind(LexiconDefinition def) { return def.Type switch { "string" => LexiconTypeKind.String, "boolean" => LexiconTypeKind.Boolean, "integer" => LexiconTypeKind.Integer, "bytes" => LexiconTypeKind.Bytes, "cid-link" => LexiconTypeKind.CidLink, "blob" => LexiconTypeKind.Blob, "object" => LexiconTypeKind.Object, "record" => LexiconTypeKind.Record, "query" => LexiconTypeKind.Query, "procedure" => LexiconTypeKind.Procedure, "subscription" => LexiconTypeKind.Subscription, "union" => LexiconTypeKind.Union, "token" => LexiconTypeKind.Token, "array" => LexiconTypeKind.Array, "ref" => LexiconTypeKind.Ref, "unknown" => LexiconTypeKind.Any, "params" => LexiconTypeKind.Params, _ => LexiconTypeKind.Unknown }; }
/// <summary> /// Looks up a type by its reference string. /// </summary> public TypeInfo? Lookup(string refString) { if (string.IsNullOrEmpty(refString)) { return null; }
_types.TryGetValue(refString, out var typeInfo); return typeInfo; }
/// <summary> /// Resolves a reference string to its C# type, handling primitives correctly. /// </summary> /// <param name="refString">The reference string (e.g., "app.bsky.actor.defs#mutedWordTarget")</param> /// <param name="currentNsid">The NSID of the current lexicon (for local refs)</param> /// <returns>The C# type string to use.</returns> public string ResolveToCSharpType(string? refString, string currentNsid) { if (string.IsNullOrEmpty(refString)) { return "object"; }
// Resolve local refs var fullRef = ResolveLocalRef(refString!, currentNsid);
// Look up the type var typeInfo = Lookup(fullRef);
if (typeInfo == null) { // Track unresolved external references if (!refString!.StartsWith("#")) { _unresolvedRefs.Add(fullRef); }
// Unknown type - fall back to generating a type name return NsidHelper.RefToFullTypeName(refString!, currentNsid, _rootNamespace); }
// Map to C# type based on kind return typeInfo.Kind switch { LexiconTypeKind.String => MapStringType(typeInfo.Definition), LexiconTypeKind.Boolean => "bool", LexiconTypeKind.Integer => "long", LexiconTypeKind.Bytes => "byte[]", LexiconTypeKind.CidLink => "CarpaNet.ATCid", LexiconTypeKind.Blob => "CarpaNet.ATBlob", LexiconTypeKind.Token => "string", // Tokens are just string constants LexiconTypeKind.Any => "System.Text.Json.JsonElement", LexiconTypeKind.Object => typeInfo.FullCSharpTypeName, LexiconTypeKind.Record => typeInfo.FullCSharpTypeName, LexiconTypeKind.Union => $"I{typeInfo.CSharpTypeName}", // Unions become interfaces // For array types, resolve the item type LexiconTypeKind.Array => ResolveArrayType(typeInfo, currentNsid), // For ref types, recursively resolve LexiconTypeKind.Ref when typeInfo.Definition?.Ref != null => ResolveToCSharpType(typeInfo.Definition.Ref, typeInfo.Nsid), _ => typeInfo.FullCSharpTypeName }; }
/// <summary> /// Resolves a lexicon ref string to a fully-qualified C# type name. /// Unlike ResolveToCSharpType, this always includes the namespace for union interfaces. /// Used by CBOR context generation where types are in namespace blocks. /// </summary> public string ResolveToFullyQualifiedCSharpType(string? refString, string currentNsid) { if (string.IsNullOrEmpty(refString)) { return "object"; }
var fullRef = ResolveLocalRef(refString!, currentNsid); var typeInfo = Lookup(fullRef);
if (typeInfo == null) { // Track unresolved external references if (!refString!.StartsWith("#")) { _unresolvedRefs.Add(fullRef); }
return NsidHelper.RefToFullTypeName(refString!, currentNsid, _rootNamespace); }
return typeInfo.Kind switch { LexiconTypeKind.String => MapStringType(typeInfo.Definition), LexiconTypeKind.Boolean => "bool", LexiconTypeKind.Integer => "long", LexiconTypeKind.Bytes => "byte[]", LexiconTypeKind.CidLink => "CarpaNet.ATCid", LexiconTypeKind.Blob => "CarpaNet.ATBlob", LexiconTypeKind.Token => "string", LexiconTypeKind.Any => "System.Text.Json.JsonElement", LexiconTypeKind.Object => typeInfo.FullCSharpTypeName, LexiconTypeKind.Record => typeInfo.FullCSharpTypeName, LexiconTypeKind.Union => $"{typeInfo.CSharpNamespace}.I{typeInfo.CSharpTypeName}", LexiconTypeKind.Array => ResolveFullyQualifiedArrayType(typeInfo, currentNsid), LexiconTypeKind.Ref when typeInfo.Definition?.Ref != null => ResolveToFullyQualifiedCSharpType(typeInfo.Definition.Ref, typeInfo.Nsid), _ => typeInfo.FullCSharpTypeName }; }
/// <summary> /// Resolves an array type to a fully-qualified C# equivalent. /// </summary> private string ResolveFullyQualifiedArrayType(TypeInfo typeInfo, string currentNsid) { if (typeInfo.Definition?.Items == null) { return "System.Collections.Generic.List<object>"; }
var items = typeInfo.Definition.Items;
var itemType = items.Type switch { "ref" when items.Ref != null => ResolveToFullyQualifiedCSharpType(items.Ref, typeInfo.Nsid), "union" when items.Refs != null => $"{typeInfo.CSharpNamespace}.I{typeInfo.CSharpTypeName}", "string" => MapStringType(items), "integer" => "long", "boolean" => "bool", _ => "object" };
return $"System.Collections.Generic.List<{itemType}>"; }
/// <summary> /// Resolves a local reference (#name) to a full reference. /// </summary> private static string ResolveLocalRef(string refString, string currentNsid) { if (refString.StartsWith("#")) { return $"{currentNsid}{refString}"; } return refString; }
/// <summary> /// Maps a string type to its C# equivalent based on format. /// </summary> private static string MapStringType(LexiconDefinition? def) { if (def?.Format == null) { return "string"; }
return def.Format switch { "at-identifier" => "CarpaNet.ATIdentifier", "at-uri" => "CarpaNet.ATUri", "cid" => "string", "datetime" => "System.DateTimeOffset", "did" => "CarpaNet.ATDid", "handle" => "CarpaNet.ATHandle", "nsid" => "string", "tid" => "string", "record-key" => "string", "uri" => "string", "language" => "string", _ => "string" }; }
/// <summary> /// Resolves an array type to its C# equivalent. /// </summary> private string ResolveArrayType(TypeInfo typeInfo, string currentNsid) { if (typeInfo.Definition?.Items == null) { return "System.Collections.Generic.List<object>"; }
var items = typeInfo.Definition.Items;
// Handle different item types var itemType = items.Type switch { "ref" when items.Ref != null => ResolveToCSharpType(items.Ref, typeInfo.Nsid), "union" when items.Refs != null => $"I{typeInfo.CSharpTypeName}", // Generate interface name for union items "string" => MapStringType(items), "integer" => "long", "boolean" => "bool", _ => "object" };
return $"System.Collections.Generic.List<{itemType}>"; }
/// <summary> /// Gets all registered types. /// </summary> public IEnumerable<TypeInfo> GetAllTypes() => _types.Values;
/// <summary> /// Gets all unresolved external references encountered during type resolution. /// Each entry is the full ref string (e.g. "app.bsky.actor.defs#profileViewBasic"). /// </summary> public IReadOnlyCollection<string> GetUnresolvedReferences() => _unresolvedRefs;
/// <summary> /// Gets types grouped by namespace. /// </summary> public Dictionary<string, List<TypeInfo>> GetTypesByNamespace() { var result = new Dictionary<string, List<TypeInfo>>();
foreach (var type in _types.Values) { if (!result.TryGetValue(type.CSharpNamespace, out var list)) { list = new List<TypeInfo>(); result[type.CSharpNamespace] = list; }
// Avoid duplicates (main definitions are registered twice) if (!list.Exists(t => t.FullRef == type.FullRef)) { list.Add(type); } }
return result; }
/// <summary> /// Checks if a reference points to a type that generates a class. /// </summary> public bool RefGeneratesClass(string refString, string currentNsid) { var fullRef = ResolveLocalRef(refString, currentNsid); var typeInfo = Lookup(fullRef); return typeInfo?.GeneratesClass ?? false; }
/// <summary> /// Checks if a reference points to a union type. /// </summary> public bool RefIsUnion(string refString, string currentNsid) { var fullRef = ResolveLocalRef(refString, currentNsid); var typeInfo = Lookup(fullRef); return typeInfo?.Kind == LexiconTypeKind.Union; }
/// <summary> /// Gets the type kind for a reference. /// </summary> public LexiconTypeKind GetRefKind(string refString, string currentNsid) { var fullRef = ResolveLocalRef(refString, currentNsid); var typeInfo = Lookup(fullRef); return typeInfo?.Kind ?? LexiconTypeKind.Unknown; }
/// <summary> /// Gets the union variants (ref strings) for a union type. /// </summary> /// <param name="refString">The reference to the union type.</param> /// <param name="currentNsid">The current NSID context for resolving local refs.</param> /// <returns>List of variant refs, or null if not a union type.</returns> public List<string>? GetUnionVariants(string refString, string currentNsid) { var fullRef = ResolveLocalRef(refString, currentNsid); var typeInfo = Lookup(fullRef);
if (typeInfo?.Kind != LexiconTypeKind.Union) { return null; }
return typeInfo.UnionRefs; }
/// <summary> /// Gets all union variants with their resolved C# type names and discriminators. /// </summary> /// <param name="refString">The reference to the union type.</param> /// <param name="currentNsid">The current NSID context for resolving local refs.</param> /// <returns>List of (CSharpTypeName, Discriminator) tuples for each variant.</returns> public List<(string CSharpType, string Discriminator)>? GetUnionVariantDetails(string refString, string currentNsid) { var variants = GetUnionVariants(refString, currentNsid); if (variants == null) { return null; }
var result = new List<(string, string)>(); var unionFullRef = ResolveLocalRef(refString, currentNsid); var unionTypeInfo = Lookup(unionFullRef);
foreach (var variantRef in variants) { var variantFullRef = ResolveLocalRef(variantRef, unionTypeInfo?.Nsid ?? currentNsid); var variantTypeInfo = Lookup(variantFullRef);
var csharpType = ResolveToCSharpType(variantRef, unionTypeInfo?.Nsid ?? currentNsid); var discriminator = variantTypeInfo?.FullRef ?? variantFullRef;
result.Add((csharpType, discriminator)); }
return result; }
/// <summary> /// Checks if a type has any union-typed properties. /// </summary> /// <param name="refString">The reference to check.</param> /// <param name="currentNsid">The current NSID context.</param> /// <returns>True if the type has union properties.</returns> public bool HasUnionProperties(string refString, string currentNsid) { var fullRef = ResolveLocalRef(refString, currentNsid); var typeInfo = Lookup(fullRef);
if (typeInfo?.Definition?.Properties == null) { return false; }
foreach (var prop in typeInfo.Definition.Properties.Values) { if (prop.Type == "union") { return true; }
if (prop.Type == "array" && prop.Items?.Type == "union") { return true; }
if (!string.IsNullOrEmpty(prop.Ref)) { var refKind = GetRefKind(prop.Ref!, typeInfo.Nsid); if (refKind == LexiconTypeKind.Union) { return true; } } }
return false; }
/// <summary> /// Gets the type discriminator (full NSID) for a type reference. /// Used for polymorphic serialization. /// </summary> /// <param name="refString">The reference string.</param> /// <param name="currentNsid">The current NSID context.</param> /// <returns>The type discriminator string.</returns> public string GetTypeDiscriminator(string refString, string currentNsid) { var fullRef = ResolveLocalRef(refString, currentNsid); var typeInfo = Lookup(fullRef); return typeInfo?.FullRef ?? fullRef; }}