Something went wrong. Try again.
.NET ATProtocol Library - Built for Source Gen
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337// <auto-generated />#nullable enable
using System;using System.Collections.Generic;using System.Collections.Immutable;using System.Linq;using System.Text;using System.Threading;using Microsoft.CodeAnalysis;using Microsoft.CodeAnalysis.Text;using CarpaNet.Generation;using CarpaNet.Models;using CarpaNet.Parsing;using CarpaNet.Utilities;
namespace CarpaNet;
/// <summary>/// Configuration options for the generator./// </summary>public sealed class GeneratorOptions{ /// <summary> /// Optional root namespace to prefix all generated namespaces. /// </summary> public string? RootNamespace { get; set; }
/// <summary> /// Whether to emit validation attributes. Default is true. /// </summary> public bool EmitValidationAttributes { get; set; } = true;
/// <summary> /// Name of the generated CBOR serializer context class. Default is "ATProtoCborContext". /// </summary> public string CborContextName { get; set; } = "ATProtoCborContext";
/// <summary> /// Name of the generated JSON resolver context class. Default is "ATProtoJsonContext". /// </summary> public string JsonContextName { get; set; } = "ATProtoJsonContext";
/// <summary> /// Whether to emit XRPC server endpoint controllers. Default is false. /// </summary> public bool EmitXrpcEndpoints { get; set; } = false;}
/// <summary>/// Roslyn Incremental Source Generator for ATProtocol Lexicon files./// </summary>[Generator(LanguageNames.CSharp)]public sealed class LexiconGenerator : IIncrementalGenerator{ public void Initialize(IncrementalGeneratorInitializationContext context) { // Filter to only files marked as LexiconFiles (via IsATProtoLexicon metadata) var lexiconFiles = context.AdditionalTextsProvider .Combine(context.AnalyzerConfigOptionsProvider) .Where(static pair => { var (file, optionsProvider) = pair; var options = optionsProvider.GetOptions(file); return options.TryGetValue("build_metadata.AdditionalFiles.IsATProtoLexicon", out var isLexicon) && isLexicon.Equals("true", StringComparison.OrdinalIgnoreCase); }) .Select(static (pair, _) => pair.Left);
// Parse each lexicon file var lexicons = lexiconFiles.Select(static (file, ct) => { var content = file.GetText(ct)?.ToString(); var document = LexiconParser.Parse(content); return (Path: file.Path, Document: document); }).Where(static x => x.Document != null);
// Collect all lexicons var allLexicons = lexicons.Collect();
// Get configuration from MSBuild properties var configOptions = context.AnalyzerConfigOptionsProvider.Select(static (provider, _) => { var options = new GeneratorOptions();
if (provider.GlobalOptions.TryGetValue("build_property.CarpaNet_RootNamespace", out var rootNs) && !string.IsNullOrWhiteSpace(rootNs)) { options.RootNamespace = rootNs; }
if (provider.GlobalOptions.TryGetValue("build_property.CarpaNet_EmitValidationAttributes", out var emitValidation) && bool.TryParse(emitValidation, out var emitValidationValue)) { options.EmitValidationAttributes = emitValidationValue; }
if (provider.GlobalOptions.TryGetValue("build_property.CarpaNet_CborContextName", out var cborContextName) && !string.IsNullOrWhiteSpace(cborContextName)) { options.CborContextName = cborContextName; }
if (provider.GlobalOptions.TryGetValue("build_property.CarpaNet_JsonContextName", out var jsonContextName) && !string.IsNullOrWhiteSpace(jsonContextName)) { options.JsonContextName = jsonContextName; }
if (provider.GlobalOptions.TryGetValue("build_property.CarpaNet_EmitXrpcEndpoints", out var emitXrpc) && bool.TryParse(emitXrpc, out var emitXrpcValue)) { options.EmitXrpcEndpoints = emitXrpcValue; }
return options; });
// Combine lexicons with configuration var combined = allLexicons.Combine(configOptions);
// Register source output context.RegisterSourceOutput(combined, static (ctx, data) => GenerateSource(ctx, data.Left, data.Right)); }
private static void GenerateSource( SourceProductionContext context, ImmutableArray<(string Path, LexiconDocument? Document)> lexicons, GeneratorOptions options) { if (lexicons.IsDefaultOrEmpty) { return; }
var rootNamespace = options.RootNamespace;
// PHASE 1: Build type registry from all documents var registry = new TypeRegistry(rootNamespace); var documents = new List<LexiconDocument>();
foreach (var (path, document) in lexicons) { if (document == null) continue; documents.Add(document); registry.RegisterDocument(document); }
// PHASE 2: Group by namespace var byNamespace = new Dictionary<string, List<(string Nsid, LexiconDocument Doc)>>();
foreach (var document in documents) { var ns = NsidHelper.ToNamespace(document.Id, rootNamespace);
if (!byNamespace.TryGetValue(ns, out var list)) { list = new List<(string, LexiconDocument)>(); byNamespace[ns] = list; }
list.Add((document.Id, document)); }
// PHASE 3: Generate source for each namespace foreach (var kvp in byNamespace) { var source = GenerateNamespaceSource(kvp.Key, kvp.Value, registry, context, options); if (!string.IsNullOrEmpty(source)) { var fileName = kvp.Key.Replace(".", "_") + ".g.cs"; context.AddSource(fileName, SourceText.From(source, Encoding.UTF8)); } }
// PHASE 3.5: Generate union interface implementations for cross-namespace types var unionMappings = CollectUnionImplementations(byNamespace, registry); var unionImplSource = GenerateUnionImplementationsSource(unionMappings); if (!string.IsNullOrEmpty(unionImplSource)) { context.AddSource("UnionImplementations.g.cs", SourceText.From(unionImplSource, Encoding.UTF8)); }
// PHASE 4: Generate API extensions file var extensionsSource = GenerateExtensionsSource(byNamespace, registry, context, options); if (!string.IsNullOrEmpty(extensionsSource)) { context.AddSource("ATProtoExtensions.g.cs", SourceText.From(extensionsSource, Encoding.UTF8)); }
// PHASE 5: Generate CBOR serialization context var cborSource = GenerateCborContextSource(byNamespace, registry, context, options); if (!string.IsNullOrEmpty(cborSource)) { context.AddSource("ATProtoCborContext.g.cs", SourceText.From(cborSource, Encoding.UTF8)); }
// PHASE 6: Generate JSON serialization context var (jsonSource, concreteTypes) = GenerateJsonContextSource(byNamespace, registry, context, options); if (!string.IsNullOrEmpty(jsonSource)) { context.AddSource($"{options.JsonContextName}.g.cs", SourceText.From(jsonSource, Encoding.UTF8)); }
// PHASE 6.5: Generate ToJson()/FromJson() serialization helper methods on concrete types var serializationMethodsSource = GenerateSerializationMethodsSource(concreteTypes, options); if (!string.IsNullOrEmpty(serializationMethodsSource)) { context.AddSource("SerializationMethods.g.cs", SourceText.From(serializationMethodsSource, Encoding.UTF8)); }
// PHASE 7: Generate client factory class var factorySource = GenerateFactorySource(options); if (!string.IsNullOrEmpty(factorySource)) { context.AddSource("ATProtoClientFactory.g.cs", SourceText.From(factorySource, Encoding.UTF8)); }
// PHASE 8: Generate XRPC endpoint controllers (opt-in) if (options.EmitXrpcEndpoints) { var xrpcSource = XrpcEndpointGenerator.Generate(byNamespace, registry, options); if (!string.IsNullOrEmpty(xrpcSource)) { context.AddSource("XrpcControllers.g.cs", SourceText.From(xrpcSource, Encoding.UTF8)); } }
// PHASE 9: Report diagnostics for unresolved lexicon references var unresolvedRefs = registry.GetUnresolvedReferences(); if (unresolvedRefs.Count > 0) { // Group by NSID (the part before #) to deduplicate and give actionable info var unresolvedByNsid = new Dictionary<string, List<string>>(StringComparer.Ordinal); foreach (var fullRef in unresolvedRefs) { var hashIndex = fullRef.IndexOf('#'); var nsid = hashIndex >= 0 ? fullRef.Substring(0, hashIndex) : fullRef; if (!unresolvedByNsid.TryGetValue(nsid, out var list)) { list = new List<string>(); unresolvedByNsid[nsid] = list; } list.Add(fullRef); }
foreach (var kvp in unresolvedByNsid) { var nsid = kvp.Key; var refs = string.Join(", ", kvp.Value); context.ReportDiagnostic(Diagnostic.Create( new DiagnosticDescriptor( "ATPG002", "Unresolved Lexicon Reference", "Lexicon '{0}' is referenced but not included in the project. Unresolved references: {1}. Add the corresponding lexicon JSON file to resolve this.", "CarpaNet", DiagnosticSeverity.Warning, isEnabledByDefault: true), Location.None, nsid, refs)); } } }
private static string GenerateNamespaceSource( string ns, List<(string Nsid, LexiconDocument Doc)> documents, TypeRegistry registry, SourceProductionContext context, GeneratorOptions options) { var sb = new SourceBuilder(); sb.WriteHeader(); sb.WriteUsing("System"); sb.WriteUsing("System.Collections.Generic"); sb.WriteUsing("CarpaNet.Validation"); sb.WriteUsing("System.Text.Json.Serialization"); sb.AppendLine(); sb.WriteNamespace(ns);
foreach (var (nsid, doc) in documents) { try { GenerateDefinitions(sb, nsid, doc, ns, registry, context); } catch (Exception ex) { context.ReportDiagnostic(Diagnostic.Create( new DiagnosticDescriptor( "ATPG001", "Generation Error", "Error generating code for {0}: {1}", "CarpaNet", DiagnosticSeverity.Warning, isEnabledByDefault: true), Location.None, nsid, ex.Message)); } }
return sb.ToString(); }
private static void GenerateDefinitions( SourceBuilder sb, string nsid, LexiconDocument doc, string currentNamespace, TypeRegistry registry, SourceProductionContext context) { foreach (var def in doc.Defs) { var defName = def.Key; var defValue = def.Value;
// Determine class name - prefix non-main defs with main type name to avoid collisions var mainTypeName = NsidHelper.ToTypeName(nsid); var className = defName == "main" ? mainTypeName : mainTypeName + NsidHelper.ToPascalCase(defName);
switch (defValue.Type) { case "record": GenerateRecordType(sb, className, defValue, nsid, registry); break;
case "query": GenerateQueryType(sb, className, defValue, nsid, currentNamespace, registry); break;
case "procedure": GenerateProcedureType(sb, className, defValue, nsid, currentNamespace, registry); break;
case "subscription": GenerateSubscriptionType(sb, className, defValue, nsid, currentNamespace, registry); break;
case "object": var objectTypeId = defName == "main" ? nsid : $"{nsid}#{defName}"; ObjectGenerator.GenerateClass(sb, className, defValue, nsid, registry, typeId: objectTypeId); sb.AppendLine(); break;
case "array": // Array types with union items need to generate the union interface if (defValue.Items?.Type == "union" && defValue.Items.Refs != null && !(defValue.Items.Closed != true && defValue.Items.Refs.Count == 0)) { var interfaceName = $"I{className}"; UnionGenerator.GenerateUnionInterface(sb, interfaceName, defValue.Items, nsid, registry); sb.AppendLine(); } break;
case "string": // String types with knownValues/enum are handled as string primitives // No class generation needed - refs resolve to "string" break;
case "token": // Tokens are string constants - refs resolve to "string" // Optionally generate a static class with the token value GenerateToken(sb, className, defValue, nsid); break; } } }
private static void GenerateRecordType( SourceBuilder sb, string className, LexiconDefinition def, string nsid, TypeRegistry registry) { if (def.Record == null) { return; }
ObjectGenerator.GenerateClass( sb, className, def.Record, nsid, registry, isRecord: true, recordType: nsid, typeId: nsid);
sb.AppendLine(); }
private static void GenerateQueryType( SourceBuilder sb, string className, LexiconDefinition def, string nsid, string currentNamespace, TypeRegistry registry) { // Generate parameters class if needed if (def.Parameters?.Properties != null && def.Parameters.Properties.Count > 0) { ApiGenerator.GenerateParametersClass(sb, className, def, nsid, registry); sb.AppendLine(); }
// Generate output class (skip if schema is a direct ref — the referenced type already exists) if (def.Output?.Schema != null && !ApiGenerator.IsOutputRef(def)) { ApiGenerator.GenerateOutputClass(sb, className, def.Output, nsid, registry); sb.AppendLine(); }
// Generate error constants if (def.Errors != null && def.Errors.Count > 0) { ApiGenerator.GenerateErrorClasses(sb, className, def.Errors, nsid); sb.AppendLine(); } }
private static void GenerateProcedureType( SourceBuilder sb, string className, LexiconDefinition def, string nsid, string currentNamespace, TypeRegistry registry) { // Generate input class (skip if schema is a direct ref — the referenced type already exists) if (def.Input?.Schema != null && !ApiGenerator.IsInputRef(def)) { ApiGenerator.GenerateInputClass(sb, className, def.Input, nsid, registry); sb.AppendLine(); }
// Generate output class (skip if schema is a direct ref — the referenced type already exists) if (def.Output?.Schema != null && !ApiGenerator.IsOutputRef(def)) { ApiGenerator.GenerateOutputClass(sb, className, def.Output, nsid, registry); sb.AppendLine(); }
// Generate error constants if (def.Errors != null && def.Errors.Count > 0) { ApiGenerator.GenerateErrorClasses(sb, className, def.Errors, nsid); sb.AppendLine(); } }
private static void GenerateSubscriptionType( SourceBuilder sb, string className, LexiconDefinition def, string nsid, string currentNamespace, TypeRegistry registry) { // Generate parameters class if needed if (def.Parameters?.Properties != null && def.Parameters.Properties.Count > 0) { ApiGenerator.GenerateParametersClass(sb, className, def, nsid, registry); sb.AppendLine(); }
// Generate message types (interface only, extension goes in extensions file) if (def.Message?.Schema != null) { ApiGenerator.GenerateSubscriptionMessageTypes(sb, className, def, nsid, registry); sb.AppendLine(); }
// Generate error constants if (def.Errors != null && def.Errors.Count > 0) { ApiGenerator.GenerateErrorClasses(sb, className, def.Errors, nsid); sb.AppendLine(); } }
private static void GenerateToken( SourceBuilder sb, string className, LexiconDefinition def, string nsid) { sb.WriteSummary(def.Description ?? $"Token: {nsid}#{className}"); sb.AppendLine($"public static class {className}Token"); sb.OpenBrace(); sb.AppendLine($"public const string Value = \"{nsid}#{NsidHelper.ToCamelCase(className)}\";"); sb.CloseBrace(); sb.AppendLine(); }
private static string GenerateExtensionsSource( Dictionary<string, List<(string Nsid, LexiconDocument Doc)>> byNamespace, TypeRegistry registry, SourceProductionContext context, GeneratorOptions options) { var sb = new SourceBuilder(); sb.WriteHeader(); sb.WriteUsing("System"); sb.WriteUsing("System.Collections.Generic"); sb.WriteUsing("System.Threading"); sb.WriteUsing("System.Threading.Tasks"); sb.AppendLine();
var extensionsNs = string.IsNullOrEmpty(options.RootNamespace) ? "CarpaNet" : $"{options.RootNamespace}"; sb.WriteNamespace(extensionsNs);
sb.WriteSummary("Extension methods for ATProto API calls."); sb.AppendLine("public static partial class ATProtoClientExtensions"); sb.OpenBrace();
foreach (var kvp in byNamespace) { var ns = kvp.Key;
foreach (var (nsid, doc) in kvp.Value) { foreach (var def in doc.Defs) { if (def.Key != "main") continue;
var className = NsidHelper.ToTypeName(nsid);
switch (def.Value.Type) { case "query": ApiGenerator.GenerateQueryExtension(sb, className, def.Value, nsid, ns, registry); sb.AppendLine(); break;
case "procedure": ApiGenerator.GenerateProcedureExtension(sb, className, def.Value, nsid, ns, registry); sb.AppendLine(); break;
case "subscription": ApiGenerator.GenerateSubscriptionExtension(sb, className, def.Value, nsid, ns, registry); sb.AppendLine(); break; } } } }
sb.CloseBrace();
return sb.ToString(); }
private static string GenerateCborContextSource( Dictionary<string, List<(string Nsid, LexiconDocument Doc)>> byNamespace, TypeRegistry registry, SourceProductionContext context, GeneratorOptions options) { var sb = new SourceBuilder(); sb.WriteHeader(); sb.AppendLine();
var generatedTypes = new HashSet<string>();
// Collect all type registrations: (ClassSuffix, QualifiedTypeName, TypeDiscriminator) var typesToRegister = new List<(string ClassSuffix, string QualifiedTypeName, string? TypeDiscriminator)>();
// Single namespace for all CBOR type info classes (matches JSON generator pattern) var contextNs = string.IsNullOrEmpty(options.RootNamespace) ? "CarpaNet.Cbor" : $"{options.RootNamespace}.Cbor";
sb.WriteNamespace(contextNs);
// Iterate all namespaces and types to generate CborTypeInfo classes foreach (var kvp in byNamespace) { var ns = kvp.Key;
foreach (var (nsid, doc) in kvp.Value) { foreach (var def in doc.Defs) { var defName = def.Key; var defValue = def.Value;
var mainTypeName = NsidHelper.ToTypeName(nsid); var className = defName == "main" ? mainTypeName : mainTypeName + NsidHelper.ToPascalCase(defName);
switch (defValue.Type) { case "record": if (defValue.Record != null) { var fullName = $"{ns}.{className}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborTypeInfo(sb, fullName, suffix, defValue.Record, nsid, registry, options, isRecord: true, generatedTypes: generatedTypes); typesToRegister.Add((suffix, fullName, nsid)); } break;
case "object": { var fullName = $"{ns}.{className}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborTypeInfo(sb, fullName, suffix, defValue, nsid, registry, options, generatedTypes: generatedTypes); typesToRegister.Add((suffix, fullName, null)); break; }
case "union": if (defValue.Refs != null && !(defValue.Closed != true && defValue.Refs.Count == 0)) { var interfaceName = $"I{className}"; var fullName = $"{ns}.{interfaceName}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborUnionTypeInfo(sb, fullName, suffix, defValue.Refs, nsid, registry, options, generatedTypes); typesToRegister.Add((suffix, fullName, null)); } break;
case "query": if (defValue.Output?.Schema != null && !ApiGenerator.IsOutputRef(defValue)) { var outputClassName = className + "Output"; var fullName = $"{ns}.{outputClassName}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborTypeInfo(sb, fullName, suffix, defValue.Output.Schema, nsid, registry, options, generatedTypes: generatedTypes); typesToRegister.Add((suffix, fullName, null)); } break;
case "procedure": if (defValue.Input?.Schema != null && !ApiGenerator.IsInputRef(defValue)) { var inputClassName = className + "Input"; var fullName = $"{ns}.{inputClassName}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborTypeInfo(sb, fullName, suffix, defValue.Input.Schema, nsid, registry, options, generatedTypes: generatedTypes); typesToRegister.Add((suffix, fullName, null)); } if (defValue.Output?.Schema != null && !ApiGenerator.IsOutputRef(defValue)) { var outputClassName = className + "Output"; var fullName = $"{ns}.{outputClassName}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborTypeInfo(sb, fullName, suffix, defValue.Output.Schema, nsid, registry, options, generatedTypes: generatedTypes); typesToRegister.Add((suffix, fullName, null)); } break;
case "subscription": if (defValue.Parameters?.Properties != null && defValue.Parameters.Properties.Count > 0) { var paramsClassName = className + "Parameters"; var fullName = $"{ns}.{paramsClassName}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborTypeInfo(sb, fullName, suffix, defValue.Parameters, nsid, registry, options, generatedTypes: generatedTypes); typesToRegister.Add((suffix, fullName, null)); } if (defValue.Message?.Schema?.Type == "union" && defValue.Message.Schema.Refs != null) { var interfaceName = $"I{className}Message"; var fullName = $"{ns}.{interfaceName}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborUnionTypeInfo(sb, fullName, suffix, defValue.Message.Schema.Refs, nsid, registry, options, generatedTypes); typesToRegister.Add((suffix, fullName, null)); } break;
case "array": if (defValue.Items?.Type == "union" && defValue.Items.Refs != null && !(defValue.Items.Closed != true && defValue.Items.Refs.Count == 0)) { var interfaceName = $"I{className}"; var fullName = $"{ns}.{interfaceName}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborUnionTypeInfo(sb, fullName, suffix, defValue.Items.Refs, nsid, registry, options, generatedTypes); typesToRegister.Add((suffix, fullName, null)); } break; } } } }
// Generate the context class sb.WriteSummary("CBOR serialization context for all AT Protocol types."); sb.AppendLine($"public partial class {options.CborContextName} : CarpaNet.Cbor.CborSerializerContext"); sb.OpenBrace();
sb.WriteSummary("Gets the default singleton instance."); sb.AppendLine($"public static new {options.CborContextName} Default {{ get; }} = new {options.CborContextName}();"); sb.AppendLine();
sb.WriteSummary("Initializes a new instance and registers all AT Protocol types."); sb.AppendLine($"public {options.CborContextName}()"); sb.OpenBrace();
foreach (var type in typesToRegister) { sb.AppendLine($"RegisterTypeInfo(new {type.ClassSuffix}CborTypeInfo());");
if (!string.IsNullOrEmpty(type.TypeDiscriminator)) { sb.AppendLine($"RegisterDerivedType(\"{type.TypeDiscriminator}\", typeof(global::{type.QualifiedTypeName}));"); } }
sb.CloseBrace(); // constructor sb.CloseBrace(); // class
return sb.ToString(); }
private static (string Source, HashSet<string> ConcreteTypes) GenerateJsonContextSource( Dictionary<string, List<(string Nsid, LexiconDocument Doc)>> byNamespace, TypeRegistry registry, SourceProductionContext context, GeneratorOptions options) { var sb = new SourceBuilder(); sb.WriteHeader();
var generatedTypes = new HashSet<string>(); var collectedPropertyTypes = new HashSet<string>(); var nestedTypeDispatch = new List<(string FullTypeName, string MethodSuffix)>(); var concreteTypes = new HashSet<string>();
// Collect all type dispatch entries: (fullCSharpTypeName, methodSuffix) var typeDispatch = new List<(string FullTypeName, string MethodSuffix)>();
var contextNs = string.IsNullOrEmpty(options.RootNamespace) ? "CarpaNet.Json" : $"{options.RootNamespace}.Json";
sb.WriteNamespace(contextNs);
sb.WriteSummary("JSON serialization context implementing IJsonTypeInfoResolver for all AT Protocol types."); sb.AppendLine($"public sealed class {options.JsonContextName} : global::System.Text.Json.Serialization.Metadata.IJsonTypeInfoResolver"); sb.OpenBrace();
sb.WriteSummary("Gets the default singleton instance."); sb.AppendLine($"public static {options.JsonContextName} Default {{ get; }} = new {options.JsonContextName}();"); sb.AppendLine();
// Default options for use by serialization helper methods sb.AppendLine("private static readonly global::System.Text.Json.JsonSerializerOptions s_defaultOptions = new global::System.Text.Json.JsonSerializerOptions"); sb.OpenBrace(); sb.AppendLine("PropertyNamingPolicy = global::System.Text.Json.JsonNamingPolicy.CamelCase,"); sb.AppendLine("DefaultIgnoreCondition = global::System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,"); sb.AppendLine($"TypeInfoResolver = Default,"); sb.CloseBrace(withSemicolon: true); sb.AppendLine();
sb.WriteSummary("Gets the default JsonSerializerOptions configured with the generated JSON type info resolver."); sb.AppendLine("public static global::System.Text.Json.JsonSerializerOptions DefaultOptions => s_defaultOptions;"); sb.AppendLine();
// Iterate all namespaces and types to generate factory methods foreach (var kvp in byNamespace) { var ns = kvp.Key;
foreach (var (nsid, doc) in kvp.Value) { foreach (var def in doc.Defs) { var defName = def.Key; var defValue = def.Value;
var mainTypeName = NsidHelper.ToTypeName(nsid); var className = defName == "main" ? mainTypeName : mainTypeName + NsidHelper.ToPascalCase(defName);
switch (defValue.Type) { case "record": if (defValue.Record != null) { var fullName = $"{ns}.{className}"; var suffix = JsonContextGenerator.ToMethodSuffix(fullName); JsonContextGenerator.GenerateJsonTypeInfo(sb, fullName, suffix, defValue.Record, nsid, registry, options, isRecord: true, generatedTypes: generatedTypes, collectedPropertyTypes: collectedPropertyTypes, nestedTypeDispatch: nestedTypeDispatch, concreteTypes: concreteTypes); typeDispatch.Add((fullName, suffix)); } break;
case "object": { var fullName = $"{ns}.{className}"; var suffix = JsonContextGenerator.ToMethodSuffix(fullName); JsonContextGenerator.GenerateJsonTypeInfo(sb, fullName, suffix, defValue, nsid, registry, options, generatedTypes: generatedTypes, collectedPropertyTypes: collectedPropertyTypes, nestedTypeDispatch: nestedTypeDispatch, concreteTypes: concreteTypes); typeDispatch.Add((fullName, suffix)); break; }
case "union": if (defValue.Refs != null && !(defValue.Closed != true && defValue.Refs.Count == 0)) { var interfaceName = $"I{className}"; var fullName = $"{ns}.{interfaceName}"; var suffix = JsonContextGenerator.ToMethodSuffix(fullName); JsonContextGenerator.GenerateJsonUnionTypeInfo(sb, fullName, suffix, defValue.Refs, nsid, registry, options, isClosed: defValue.Closed == true, generatedTypes: generatedTypes, nestedTypeDispatch: nestedTypeDispatch); typeDispatch.Add((fullName, suffix)); } break;
case "query": if (defValue.Output?.Schema != null && !ApiGenerator.IsOutputRef(defValue)) { var outputClassName = className + "Output"; var fullName = $"{ns}.{outputClassName}"; var suffix = JsonContextGenerator.ToMethodSuffix(fullName); JsonContextGenerator.GenerateJsonTypeInfo(sb, fullName, suffix, defValue.Output.Schema, nsid, registry, options, generatedTypes: generatedTypes, collectedPropertyTypes: collectedPropertyTypes, nestedTypeDispatch: nestedTypeDispatch, concreteTypes: concreteTypes); typeDispatch.Add((fullName, suffix)); } break;
case "procedure": if (defValue.Input?.Schema != null && !ApiGenerator.IsInputRef(defValue)) { var inputClassName = className + "Input"; var fullName = $"{ns}.{inputClassName}"; var suffix = JsonContextGenerator.ToMethodSuffix(fullName); JsonContextGenerator.GenerateJsonTypeInfo(sb, fullName, suffix, defValue.Input.Schema, nsid, registry, options, generatedTypes: generatedTypes, collectedPropertyTypes: collectedPropertyTypes, nestedTypeDispatch: nestedTypeDispatch, concreteTypes: concreteTypes); typeDispatch.Add((fullName, suffix)); } if (defValue.Output?.Schema != null && !ApiGenerator.IsOutputRef(defValue)) { var outputClassName = className + "Output"; var fullName = $"{ns}.{outputClassName}"; var suffix = JsonContextGenerator.ToMethodSuffix(fullName); JsonContextGenerator.GenerateJsonTypeInfo(sb, fullName, suffix, defValue.Output.Schema, nsid, registry, options, generatedTypes: generatedTypes, collectedPropertyTypes: collectedPropertyTypes, nestedTypeDispatch: nestedTypeDispatch, concreteTypes: concreteTypes); typeDispatch.Add((fullName, suffix)); } break;
case "subscription": if (defValue.Message?.Schema?.Type == "union" && defValue.Message.Schema.Refs != null) { var interfaceName = $"I{className}Message"; var fullName = $"{ns}.{interfaceName}"; var suffix = JsonContextGenerator.ToMethodSuffix(fullName); JsonContextGenerator.GenerateJsonUnionTypeInfo(sb, fullName, suffix, defValue.Message.Schema.Refs, nsid, registry, options, isClosed: defValue.Message.Schema.Closed == true, generatedTypes: generatedTypes, nestedTypeDispatch: nestedTypeDispatch); typeDispatch.Add((fullName, suffix)); } break;
case "array": if (defValue.Items?.Type == "union" && defValue.Items.Refs != null && !(defValue.Items.Closed != true && defValue.Items.Refs.Count == 0)) { var interfaceName = $"I{className}"; var fullName = $"{ns}.{interfaceName}"; var suffix = JsonContextGenerator.ToMethodSuffix(fullName); JsonContextGenerator.GenerateJsonUnionTypeInfo(sb, fullName, suffix, defValue.Items.Refs, nsid, registry, options, isClosed: defValue.Items.Closed == true, generatedTypes: generatedTypes, nestedTypeDispatch: nestedTypeDispatch); typeDispatch.Add((fullName, suffix)); } break; } } } }
// Merge nested type dispatch entries (inline objects/unions generated recursively) typeDispatch.AddRange(nestedTypeDispatch);
// Generate built-in type info factories for leaf property types (primitives, runtime types, List<T>) var generatedObjectTypeNames = new HashSet<string>(typeDispatch.Select(t => t.FullTypeName.Replace("@", ""))); var builtInDispatchLines = JsonContextGenerator.GenerateBuiltInTypeInfos(sb, collectedPropertyTypes, generatedObjectTypeNames);
// Generate the GetTypeInfo dispatch method sb.WriteSummary("Gets the JSON type info for the specified type, or null if not handled."); sb.AppendLine("public global::System.Text.Json.Serialization.Metadata.JsonTypeInfo? GetTypeInfo(global::System.Type type, global::System.Text.Json.JsonSerializerOptions options)"); sb.OpenBrace();
foreach (var entry in typeDispatch) { sb.AppendLine($"if (type == typeof(global::{entry.FullTypeName})) return Create_{entry.MethodSuffix}_TypeInfo(options);"); }
// Built-in type dispatch (primitives, runtime types, nullables, collections) foreach (var line in builtInDispatchLines) { sb.AppendLine(line); }
sb.AppendLine("return null;"); sb.CloseBrace();
sb.CloseBrace(); // class sb.AppendLine();
return (sb.ToString(), concreteTypes); }
private static string GenerateSerializationMethodsSource( HashSet<string> concreteTypes, GeneratorOptions options) { if (concreteTypes.Count == 0) { return string.Empty; }
var contextNs = string.IsNullOrEmpty(options.RootNamespace) ? "CarpaNet.Json" : $"{options.RootNamespace}.Json";
var sb = new SourceBuilder(); sb.WriteHeader();
// Group types by namespace var byNamespace = concreteTypes .OrderBy(t => t) .GroupBy(t => t.Contains(".") ? t.Substring(0, t.LastIndexOf('.')) : "");
foreach (var nsGroup in byNamespace) { var ns = nsGroup.Key; if (!string.IsNullOrEmpty(ns)) { sb.WriteNamespaceBlock(ns); }
foreach (var fullTypeName in nsGroup) { var shortName = fullTypeName.Contains(".") ? fullTypeName.Substring(fullTypeName.LastIndexOf('.') + 1) : fullTypeName;
sb.AppendLine($"partial class {shortName}"); sb.OpenBrace();
// ToJson() sb.WriteSummary("Serializes this instance to a <see cref=\"global::System.Text.Json.JsonElement\"/>."); sb.AppendLine("public global::System.Text.Json.JsonElement ToJson()"); sb.OpenBrace(); sb.AppendLine("return global::System.Text.Json.JsonSerializer.SerializeToElement("); sb.Indent(); sb.AppendLine("this,"); sb.AppendLine($"(global::System.Text.Json.Serialization.Metadata.JsonTypeInfo<{shortName}>)"); sb.AppendLine($" global::{contextNs}.{options.JsonContextName}.DefaultOptions.GetTypeInfo(typeof({shortName}))!);"); sb.Unindent(); sb.CloseBrace(); sb.AppendLine();
// FromJson() sb.WriteSummary("Deserializes a <see cref=\"global::System.Text.Json.JsonElement\"/> to an instance of this type."); sb.AppendLine($"public static {shortName}? FromJson(global::System.Text.Json.JsonElement element)"); sb.OpenBrace(); sb.AppendLine($"return global::System.Text.Json.JsonSerializer.Deserialize("); sb.Indent(); sb.AppendLine("element,"); sb.AppendLine($"(global::System.Text.Json.Serialization.Metadata.JsonTypeInfo<{shortName}>)"); sb.AppendLine($" global::{contextNs}.{options.JsonContextName}.DefaultOptions.GetTypeInfo(typeof({shortName}))!);"); sb.Unindent(); sb.CloseBrace();
sb.CloseBrace(); // partial class sb.AppendLine(); }
if (!string.IsNullOrEmpty(ns)) { sb.CloseBrace(); // namespace sb.AppendLine(); } }
return sb.ToString(); }
/// <summary> /// Collects all union interface-to-implementation mappings across all namespaces. /// Returns a mapping of fully-qualified derived type name -> set of fully-qualified interface names. /// </summary> private static Dictionary<string, HashSet<string>> CollectUnionImplementations( Dictionary<string, List<(string Nsid, LexiconDocument Doc)>> byNamespace, TypeRegistry registry) { var result = new Dictionary<string, HashSet<string>>();
void AddMapping(string derivedType, string interfaceName) { if (!result.TryGetValue(derivedType, out var set)) { set = new HashSet<string>(); result[derivedType] = set; } set.Add(interfaceName); }
void ProcessUnionRefs(List<string> refs, string fullyQualifiedInterfaceName, string currentNsid) { foreach (var refString in refs) { var fullRef = refString.StartsWith("#") ? $"{currentNsid}{refString}" : refString; var typeInfo = registry.Lookup(fullRef);
// Only add mapping for concrete class types (object/record) if (typeInfo != null && (typeInfo.Kind == LexiconTypeKind.Object || typeInfo.Kind == LexiconTypeKind.Record)) { AddMapping(typeInfo.FullCSharpTypeName, fullyQualifiedInterfaceName); } } }
void ProcessObjectProperties(Dictionary<string, LexiconDefinition> properties, string className, string ns, string currentNsid) { foreach (var prop in properties) { if (prop.Value.Type == "union" && prop.Value.Refs != null && !(prop.Value.Closed != true && prop.Value.Refs.Count == 0)) { var cleanClassName = NsidHelper.StripEscapePrefix(className); var cleanPropertyName = NsidHelper.StripEscapePrefix(NsidHelper.ToPascalCase(prop.Key)); var interfaceName = $"I{cleanClassName}{cleanPropertyName}"; var fullyQualifiedInterface = $"{ns}.{interfaceName}"; ProcessUnionRefs(prop.Value.Refs, fullyQualifiedInterface, currentNsid); }
if (prop.Value.Type == "array" && prop.Value.Items?.Type == "union" && prop.Value.Items.Refs != null && !(prop.Value.Items.Closed != true && prop.Value.Items.Refs.Count == 0)) { var cleanClassName = NsidHelper.StripEscapePrefix(className); var cleanPropertyName = NsidHelper.StripEscapePrefix(NsidHelper.ToPascalCase(prop.Key)); var interfaceName = $"I{cleanClassName}{cleanPropertyName}"; var fullyQualifiedInterface = $"{ns}.{interfaceName}"; ProcessUnionRefs(prop.Value.Items.Refs, fullyQualifiedInterface, currentNsid); } } }
foreach (var kvp in byNamespace) { var ns = kvp.Key;
foreach (var (nsid, doc) in kvp.Value) { foreach (var def in doc.Defs) { var defName = def.Key; var defValue = def.Value;
var mainTypeName = NsidHelper.ToTypeName(nsid); var className = defName == "main" ? mainTypeName : mainTypeName + NsidHelper.ToPascalCase(defName);
switch (defValue.Type) { case "record": if (defValue.Record?.Properties != null) { ProcessObjectProperties(defValue.Record.Properties, className, ns, nsid); } break;
case "object": if (defValue.Properties != null) { ProcessObjectProperties(defValue.Properties, className, ns, nsid); } break;
case "union": if (defValue.Refs != null && !(defValue.Closed != true && defValue.Refs.Count == 0)) { var interfaceName = $"I{className}"; var fullyQualifiedInterface = $"{ns}.{interfaceName}"; ProcessUnionRefs(defValue.Refs, fullyQualifiedInterface, nsid); } break;
case "array": if (defValue.Items?.Type == "union" && defValue.Items.Refs != null && !(defValue.Items.Closed != true && defValue.Items.Refs.Count == 0)) { var interfaceName = $"I{className}"; var fullyQualifiedInterface = $"{ns}.{interfaceName}"; ProcessUnionRefs(defValue.Items.Refs, fullyQualifiedInterface, nsid); } break;
case "query": if (defValue.Output?.Schema != null && !ApiGenerator.IsOutputRef(defValue) && defValue.Output.Schema.Properties != null) { var outputClassName = className + "Output"; ProcessObjectProperties(defValue.Output.Schema.Properties, outputClassName, ns, nsid); } break;
case "procedure": if (defValue.Input?.Schema != null && !ApiGenerator.IsInputRef(defValue) && defValue.Input.Schema.Properties != null) { var inputClassName = className + "Input"; ProcessObjectProperties(defValue.Input.Schema.Properties, inputClassName, ns, nsid); } if (defValue.Output?.Schema != null && !ApiGenerator.IsOutputRef(defValue) && defValue.Output.Schema.Properties != null) { var outputClassName = className + "Output"; ProcessObjectProperties(defValue.Output.Schema.Properties, outputClassName, ns, nsid); } break;
case "subscription": if (defValue.Message?.Schema?.Type == "union" && defValue.Message.Schema.Refs != null) { var interfaceName = $"I{className}Message"; var fullyQualifiedInterface = $"{ns}.{interfaceName}"; ProcessUnionRefs(defValue.Message.Schema.Refs, fullyQualifiedInterface, nsid); } break; } } } }
return result; }
/// <summary> /// Generates partial class declarations that add union interface implementations. /// </summary> private static string GenerateUnionImplementationsSource( Dictionary<string, HashSet<string>> unionMappings) { if (unionMappings.Count == 0) return string.Empty;
var sb = new SourceBuilder(); sb.WriteHeader();
// Group by namespace of the derived type var byNamespace = new Dictionary<string, List<(string ClassName, HashSet<string> Interfaces)>>();
foreach (var kvp in unionMappings) { var lastDot = kvp.Key.LastIndexOf('.'); if (lastDot < 0) continue;
var ns = kvp.Key.Substring(0, lastDot); var className = kvp.Key.Substring(lastDot + 1);
if (!byNamespace.TryGetValue(ns, out var list)) { list = new List<(string, HashSet<string>)>(); byNamespace[ns] = list; }
list.Add((className, kvp.Value)); }
foreach (var nsKvp in byNamespace) { sb.WriteNamespaceBlock(nsKvp.Key);
foreach (var (className, interfaces) in nsKvp.Value) { var interfaceList = string.Join(", ", interfaces.OrderBy(i => i).Select(i => $"global::{i}")); sb.AppendLine($"public partial class {className} : {interfaceList}"); sb.OpenBrace(); sb.CloseBrace(); sb.AppendLine(); }
sb.CloseBrace(); // namespace sb.AppendLine(); }
return sb.ToString(); }
private static string GenerateFactorySource(GeneratorOptions options) { var sb = new SourceBuilder(); sb.WriteHeader(); sb.WriteUsing("System"); sb.WriteUsing("System.Collections.Generic"); sb.WriteUsing("System.Net.Http"); sb.WriteUsing("System.Text.Json"); sb.WriteUsing("System.Text.Json.Serialization"); sb.WriteUsing("System.Text.Json.Serialization.Metadata"); sb.WriteUsing("System.Threading"); sb.WriteUsing("System.Threading.Tasks"); sb.WriteUsing("CarpaNet"); sb.WriteUsing("CarpaNet.Cbor"); sb.WriteUsing("CarpaNet.Identity"); sb.WriteUsing("CarpaNet.Storage"); sb.AppendLine();
var jsonContextNs = string.IsNullOrEmpty(options.RootNamespace) ? "CarpaNet.Json" : $"{options.RootNamespace}.Json";
var cborContextNs = string.IsNullOrEmpty(options.RootNamespace) ? "CarpaNet.Cbor" : $"{options.RootNamespace}.Cbor";
var factoryNs = string.IsNullOrEmpty(options.RootNamespace) ? "CarpaNet" : $"{options.RootNamespace}";
sb.WriteNamespace(factoryNs);
sb.WriteSummary("Factory class that creates pre-configured ATProto client instances with the generated JSON and CBOR serialization contexts."); sb.AppendLine("public static class ATProtoClientFactory"); sb.OpenBrace();
// CreateJsonOptions sb.WriteSummary("Creates JsonSerializerOptions configured with the generated JSON type info resolver."); sb.AppendLine("public static JsonSerializerOptions CreateJsonOptions()"); sb.OpenBrace(); sb.AppendLine($"return global::{jsonContextNs}.{options.JsonContextName}.DefaultOptions;"); sb.CloseBrace(); sb.AppendLine();
// Create sb.WriteSummary("Creates an ATProtoClient with the generated serialization contexts. By default, creates a public (unauthenticated) client."); sb.AppendLine("public static ATProtoClient Create(ATProtoClientOptions? options = null)"); sb.OpenBrace(); sb.AppendLine("options ??= new ATProtoClientOptions { JsonOptions = CreateJsonOptions(), CborContext = global::" + cborContextNs + "." + options.CborContextName + ".Default };"); sb.AppendLine("return ATProtoClient.Create(options);"); sb.CloseBrace(); sb.AppendLine();
// CreateWithSessionAsync sb.WriteSummary("Creates an authenticated ATProtoClient with the generated serialization contexts."); sb.AppendLine("public static async Task<ATProtoClient> CreateWithSessionAsync("); sb.Indent(); sb.AppendLine("string identifier, string password,"); sb.AppendLine("Uri? serviceUrl = null,"); sb.AppendLine("ATProtoClientOptions? options = null,"); sb.AppendLine("CancellationToken cancellationToken = default)"); sb.Unindent(); sb.OpenBrace(); sb.AppendLine("options ??= new ATProtoClientOptions { JsonOptions = CreateJsonOptions(), CborContext = global::" + cborContextNs + "." + options.CborContextName + ".Default };"); sb.AppendLine("return await ATProtoClient.CreateWithSessionAsync("); sb.Indent(); sb.AppendLine("identifier, password, serviceUrl, options, cancellationToken);"); sb.Unindent(); sb.CloseBrace(); sb.AppendLine();
// CreateClient sb.WriteSummary("Creates an ATProtoClient with the generated serialization contexts."); sb.AppendLine("public static ATProtoClient CreateClient("); sb.Indent(); sb.AppendLine("HttpClient? httpClient = null,"); sb.AppendLine("Uri? baseUrl = null,"); sb.AppendLine("IdentityResolver? identityResolver = null,"); sb.AppendLine("IReadOnlyList<string>? labelerDids = null)"); sb.Unindent(); sb.OpenBrace(); sb.AppendLine("return ATProtoClient.Create(new ATProtoClientOptions"); sb.OpenBrace(); sb.AppendLine("HttpClient = httpClient,"); sb.AppendLine("JsonOptions = CreateJsonOptions(),"); sb.AppendLine($"CborContext = global::{cborContextNs}.{options.CborContextName}.Default,"); sb.AppendLine("BaseUrl = baseUrl,"); sb.AppendLine("IdentityResolver = identityResolver,"); sb.AppendLine("LabelerDids = labelerDids"); sb.CloseBrace(); sb.AppendLine(");"); sb.CloseBrace(); sb.AppendLine();
// CreateSessionClient sb.WriteSummary("Creates an ATProtoClient configured for session-based authentication with the generated serialization contexts."); sb.AppendLine("public static ATProtoClient CreateSessionClient("); sb.Indent(); sb.AppendLine("HttpClient? httpClient = null,"); sb.AppendLine("IdentityResolver? identityResolver = null,"); sb.AppendLine("IReadOnlyList<string>? labelerDids = null)"); sb.Unindent(); sb.OpenBrace(); sb.AppendLine("return ATProtoClient.Create(new ATProtoClientOptions"); sb.OpenBrace(); sb.AppendLine("HttpClient = httpClient,"); sb.AppendLine("JsonOptions = CreateJsonOptions(),"); sb.AppendLine($"CborContext = global::{cborContextNs}.{options.CborContextName}.Default,"); sb.AppendLine("IdentityResolver = identityResolver,"); sb.AppendLine("LabelerDids = labelerDids"); sb.CloseBrace(); sb.AppendLine(");"); sb.CloseBrace(); sb.AppendLine();
// CreateSessionClient with ISessionStore sb.WriteSummary("Creates an ATProtoClient configured for session-based authentication with the generated serialization contexts and a session store for automatic persistence."); sb.AppendLine("public static ATProtoClient CreateSessionClient("); sb.Indent(); sb.AppendLine("ISessionStore sessionStore,"); sb.AppendLine("HttpClient? httpClient = null,"); sb.AppendLine("IdentityResolver? identityResolver = null,"); sb.AppendLine("IReadOnlyList<string>? labelerDids = null)"); sb.Unindent(); sb.OpenBrace(); sb.AppendLine("return ATProtoClient.Create(new ATProtoClientOptions"); sb.OpenBrace(); sb.AppendLine("HttpClient = httpClient,"); sb.AppendLine("JsonOptions = CreateJsonOptions(),"); sb.AppendLine($"CborContext = global::{cborContextNs}.{options.CborContextName}.Default,"); sb.AppendLine("IdentityResolver = identityResolver,"); sb.AppendLine("LabelerDids = labelerDids,"); sb.AppendLine("SessionStore = sessionStore"); sb.CloseBrace(); sb.AppendLine(");"); sb.CloseBrace();
sb.CloseBrace(); // class sb.AppendLine();
return sb.ToString(); }}