//
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using CarpaNet.Models;
using CarpaNet.Utilities;
namespace CarpaNet.Generation;
///
/// Generates abstract ASP.NET controller classes for XRPC server endpoints.
///
public static class XrpcEndpointGenerator
{
///
/// Generates all XRPC controllers from the given namespace-grouped lexicons.
///
public static string Generate(
Dictionary> byNamespace,
TypeRegistry registry,
GeneratorOptions options)
{
// Collect all query/procedure definitions and group by controller (first 3 NSID segments)
var controllerGroups = new Dictionary>();
foreach (var kvp in byNamespace)
{
var ns = kvp.Key;
foreach (var (nsid, doc) in kvp.Value)
{
if (doc.Defs == null) continue;
foreach (var def in doc.Defs)
{
if (def.Value.Type != "query" && def.Value.Type != "procedure")
continue;
var groupKey = GetControllerGroup(nsid);
if (groupKey == null) continue;
if (!controllerGroups.TryGetValue(groupKey, out var list))
{
list = new List();
controllerGroups[groupKey] = list;
}
var className = NsidHelper.ToTypeName(nsid);
list.Add(new EndpointInfo
{
Nsid = nsid,
ClassName = className,
Definition = def.Value,
Namespace = ns,
});
}
}
}
if (controllerGroups.Count == 0)
return string.Empty;
var sb = new SourceBuilder();
sb.WriteHeader();
foreach (var kvp in controllerGroups.OrderBy(x => x.Key))
{
var groupNsid = kvp.Key;
var endpoints = kvp.Value;
var controllerName = GetControllerName(groupNsid);
var controllerNamespace = GetControllerNamespace(groupNsid, options.RootNamespace);
sb.WriteNamespaceBlock(controllerNamespace);
GenerateController(sb, groupNsid, controllerName, endpoints, registry, options);
sb.CloseBrace(); // namespace
sb.AppendLine();
}
return sb.ToString();
}
///
/// Extracts the controller group from an NSID (first 3 segments).
/// For example, "app.bsky.actor.getProfile" returns "app.bsky.actor".
///
public static string? GetControllerGroup(string nsid)
{
var parts = nsid.Split('.');
if (parts.Length < 4) return null;
return $"{parts[0]}.{parts[1]}.{parts[2]}";
}
///
/// Gets the controller class name from a group NSID.
/// For example, "app.bsky.actor" returns "ActorController".
///
public static string GetControllerName(string groupNsid)
{
var parts = groupNsid.Split('.');
return NsidHelper.ToPascalCase(parts[parts.Length - 1]) + "Controller";
}
///
/// Gets the namespace for a controller.
/// For example, "app.bsky.actor" with root "MyApp" returns "MyApp.Xrpc.AppBsky.Actor".
///
public static string GetControllerNamespace(string groupNsid, string? rootNamespace)
{
var nsidNamespace = NsidHelper.ToNamespace(groupNsid + ".placeholder", rootNamespace);
if (rootNamespace != null)
return $"{rootNamespace}.Xrpc.{nsidNamespace.Substring(rootNamespace.Length + 1)}";
return $"Xrpc.{nsidNamespace}";
}
///
/// Generates an abstract controller class for a group of endpoints.
///
internal static void GenerateController(
SourceBuilder sb,
string groupNsid,
string controllerName,
List endpoints,
TypeRegistry registry,
GeneratorOptions options)
{
sb.WriteSummary($"Abstract XRPC controller for {groupNsid} endpoints.");
sb.WriteAttribute("Microsoft.AspNetCore.Mvc.ApiController");
sb.AppendLine($"public abstract partial class {controllerName} : Microsoft.AspNetCore.Mvc.ControllerBase");
sb.OpenBrace();
for (int i = 0; i < endpoints.Count; i++)
{
var endpoint = endpoints[i];
if (i > 0)
sb.AppendLine();
if (endpoint.Definition.Type == "query")
GenerateQueryMethod(sb, endpoint, registry, options);
else if (endpoint.Definition.Type == "procedure")
GenerateProcedureMethod(sb, endpoint, registry, options);
}
sb.CloseBrace(); // class
}
///
/// Generates an abstract method for a query (HTTP GET) endpoint.
///
internal static void GenerateQueryMethod(
SourceBuilder sb,
EndpointInfo endpoint,
TypeRegistry registry,
GeneratorOptions options)
{
var def = endpoint.Definition;
var hasOutput = def.Output?.Schema != null;
var returnType = GetReturnType(endpoint, registry, hasOutput);
var methodName = GetMethodName(endpoint.Nsid) + "Async";
sb.WriteSummary(def.Description ?? $"XRPC query: {endpoint.Nsid}");
sb.WriteAttribute($"Microsoft.AspNetCore.Mvc.HttpGet(\"/xrpc/{endpoint.Nsid}\")");
sb.Append("");
sb.AppendIndent();
sb.Append($"public abstract System.Threading.Tasks.Task<{returnType}> {methodName}(");
var parameters = BuildQueryParameters(def, endpoint.Nsid, registry);
WriteParameterList(sb, parameters);
sb.Append(");\n");
}
///
/// Generates an abstract method for a procedure (HTTP POST) endpoint.
///
internal static void GenerateProcedureMethod(
SourceBuilder sb,
EndpointInfo endpoint,
TypeRegistry registry,
GeneratorOptions options)
{
var def = endpoint.Definition;
var hasInput = def.Input?.Schema != null;
var hasOutput = def.Output?.Schema != null;
var returnType = GetReturnType(endpoint, registry, hasOutput);
var methodName = GetMethodName(endpoint.Nsid) + "Async";
sb.WriteSummary(def.Description ?? $"XRPC procedure: {endpoint.Nsid}");
sb.WriteAttribute($"Microsoft.AspNetCore.Mvc.HttpPost(\"/xrpc/{endpoint.Nsid}\")");
sb.Append("");
sb.AppendIndent();
sb.Append($"public abstract System.Threading.Tasks.Task<{returnType}> {methodName}(");
var parameters = new List();
if (hasInput)
{
var inputType = ApiGenerator.ResolveInputType(def, endpoint.Nsid, endpoint.Namespace, endpoint.ClassName, registry);
parameters.Add(new ParameterDef
{
Attribute = "Microsoft.AspNetCore.Mvc.FromBody",
Type = $"global::{inputType}",
Name = "input",
IsOptional = false,
});
}
parameters.Add(new ParameterDef
{
Type = "System.Threading.CancellationToken",
Name = "cancellationToken",
DefaultValue = "default",
IsOptional = true,
});
WriteParameterList(sb, parameters);
sb.Append(");\n");
}
///
/// Builds the parameter list for a query method from the definition's parameters.
///
private static List BuildQueryParameters(
LexiconDefinition def,
string currentNsid,
TypeRegistry registry)
{
var parameters = new List();
if (def.Parameters?.Properties != null)
{
var requiredProps = def.Parameters.Required ?? new List();
foreach (var prop in def.Parameters.Properties)
{
var isRequired = requiredProps.Contains(prop.Key);
var csharpType = ResolveParameterType(prop.Value, currentNsid, registry);
var isArray = prop.Value.Type == "array";
if (!isRequired && !isArray)
{
csharpType = MakeNullable(csharpType);
}
parameters.Add(new ParameterDef
{
Attribute = "Microsoft.AspNetCore.Mvc.FromQuery",
AttributeArgs = $"Name = \"{prop.Key}\"",
Type = csharpType,
Name = NsidHelper.EscapeIdentifier(NsidHelper.ToCamelCase(prop.Key)),
DefaultValue = isRequired ? null : "default",
IsOptional = !isRequired,
});
}
}
parameters.Add(new ParameterDef
{
Type = "System.Threading.CancellationToken",
Name = "cancellationToken",
DefaultValue = "default",
IsOptional = true,
});
return parameters;
}
///
/// Resolves a parameter definition to its C# type.
///
internal static string ResolveParameterType(LexiconDefinition def, string currentNsid, TypeRegistry registry)
{
return def.Type switch
{
"boolean" => "bool",
"integer" => "long",
"string" => MapStringFormat(def),
"array" => ResolveArrayParameterType(def, currentNsid, registry),
"ref" when def.Ref != null => registry.ResolveToCSharpType(def.Ref, currentNsid),
_ => "string",
};
}
///
/// Maps a string type's format to a C# type for query parameters.
///
private static string MapStringFormat(LexiconDefinition def)
{
if (def.Format == null)
return "string";
return def.Format switch
{
"at-identifier" => "string",
"at-uri" => "string",
"cid" => "string",
"datetime" => "string",
"did" => "string",
"handle" => "string",
"nsid" => "string",
"tid" => "string",
"record-key" => "string",
"uri" => "string",
"language" => "string",
_ => "string",
};
}
///
/// Resolves an array parameter type.
///
private static string ResolveArrayParameterType(LexiconDefinition def, string currentNsid, TypeRegistry registry)
{
if (def.Items == null)
return "System.Collections.Generic.List";
var itemType = ResolveParameterType(def.Items, currentNsid, registry);
return $"System.Collections.Generic.List<{itemType}>";
}
///
/// Gets the return type for an endpoint.
///
private static string GetReturnType(EndpointInfo endpoint, TypeRegistry registry, bool hasOutput)
{
if (hasOutput)
{
var outputType = ApiGenerator.ResolveOutputType(
endpoint.Definition, endpoint.Nsid, endpoint.Namespace, endpoint.ClassName, registry);
return $"Microsoft.AspNetCore.Http.HttpResults.Results, CarpaNet.AspNetCore.ATErrorResult>";
}
return "Microsoft.AspNetCore.Http.HttpResults.Results";
}
///
/// Gets the method name from an NSID. Uses the last segment in PascalCase.
/// For example, "app.bsky.actor.getProfile" returns "GetProfile".
///
public static string GetMethodName(string nsid)
{
var parts = nsid.Split('.');
return NsidHelper.ToPascalCase(parts[parts.Length - 1]);
}
///
/// Writes a parameter list inline.
///
private static void WriteParameterList(SourceBuilder sb, List parameters)
{
if (parameters.Count == 0)
return;
sb.Append("\n");
sb.Indent();
for (int i = 0; i < parameters.Count; i++)
{
var param = parameters[i];
sb.AppendIndent();
if (param.Attribute != null)
{
if (param.AttributeArgs != null)
sb.Append($"[{param.Attribute}({param.AttributeArgs})] ");
else
sb.Append($"[{param.Attribute}] ");
}
sb.Append($"{param.Type} {param.Name}");
if (param.DefaultValue != null)
sb.Append($" = {param.DefaultValue}");
if (i < parameters.Count - 1)
sb.Append(",");
sb.Append("\n");
}
sb.Unindent();
sb.AppendIndent();
}
///
/// Makes a type nullable by appending '?' if not already nullable.
///
private static string MakeNullable(string type)
{
if (type.EndsWith("?"))
return type;
// Reference types that are already nullable by convention
if (type.StartsWith("System.Collections.Generic.List<"))
return type + "?";
return type + "?";
}
///
/// Represents a method parameter to be emitted.
///
internal sealed class ParameterDef
{
public string? Attribute { get; set; }
public string? AttributeArgs { get; set; }
public string Type { get; set; } = "object";
public string Name { get; set; } = "param";
public string? DefaultValue { get; set; }
public bool IsOptional { get; set; }
}
///
/// Represents a collected endpoint to generate.
///
internal sealed class EndpointInfo
{
public string Nsid { get; set; } = "";
public string ClassName { get; set; } = "";
public LexiconDefinition Definition { get; set; } = new();
public string Namespace { get; set; } = "";
}
}