using System.Text.Json; using System.Text.RegularExpressions; namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; internal static class MdpApiPullImport { private static readonly Regex Token = new("""'([^']*)'|"([^"]*)"|([^\s'"]+)"""); internal static MdpApiPullPlan Read(string kind, string text, string? selection) { if (string.IsNullOrWhiteSpace(text) || text.Length > 65536) throw new MdpApiPullException("PULL_IMPORT_INVALID"); if (kind == "curl") return Curl(text); using var json = JsonDocument.Parse(text, new JsonDocumentOptions { MaxDepth = 32 }); return kind switch { "openapi" => OpenApi(json.RootElement, selection), "postman" => Postman(json.RootElement, selection), _ => throw new MdpApiPullException("PULL_IMPORT_INVALID") }; } private static MdpApiPullPlan OpenApi(JsonElement root, string? selection) { var server = First(MdpApiPullPlan.Value(root, "servers")); var endpoint = Text(server, "url"); var paths = MdpApiPullPlan.Value(root, "paths"); if (endpoint is null || paths.ValueKind != JsonValueKind.Object) throw new MdpApiPullException("PULL_IMPORT_INVALID"); var candidates = new List<(string Path, string Method, JsonElement Operation)>(); foreach (var path in paths.EnumerateObject()) { foreach (var method in new[] { "get", "post" }) if (path.Value.ValueKind == JsonValueKind.Object && path.Value.TryGetProperty(method, out var operation) && operation.ValueKind == JsonValueKind.Object) candidates.Add((path.Name, method, operation)); } var chosen = Choose(candidates, candidate => candidate.Method.ToUpperInvariant() + " " + candidate.Path, selection); var query = MdpApiPullPlan.Value(chosen.Operation, "parameters"); var names = query.ValueKind == JsonValueKind.Array ? query.EnumerateArray() .Where(parameter => Text(parameter, "in") == "query").Select(parameter => Text(parameter, "name")).ToArray() : []; var mode = names.Contains("cursor") ? "cursor" : names.Contains("offset") ? "offset" : names.Contains("page") ? "page" : "single"; var wire = Build(endpoint.TrimEnd('/') + chosen.Path, chosen.Method); var security = MdpApiPullPlan.Value(chosen.Operation, "security"); var requirements = First(security.ValueKind == JsonValueKind.Undefined ? MdpApiPullPlan.Value(root, "security") : security); if (requirements.ValueKind == JsonValueKind.Object) { var identifier = requirements.EnumerateObject().Select(entry => entry.Name).FirstOrDefault(); var schemes = MdpApiPullPlan.Value(root, "components.securitySchemes"); if (identifier is not null && schemes.ValueKind == JsonValueKind.Object && schemes.TryGetProperty(identifier, out var scheme)) wire = wire with { Auth = AuthKind(Text(scheme, "type")) is "none" && Text(scheme, "scheme") == "basic" ? "basic" : AuthKind(Text(scheme, "type")) }; } return wire with { Mode = mode, PositionParameter = mode == "single" ? "page" : mode, PageSizeParameter = names.Contains("pageSize") ? "pageSize" : "limit", FirstPosition = mode == "offset" ? 0 : 1, NextCursorPath = mode == "cursor" ? "nextCursor" : null, ResponsePath = OpenApiResponsePath(chosen.Operation) }; } private static string OpenApiResponsePath(JsonElement operation) { var schema = MdpApiPullPlan.Value(operation, "responses.200.content.application/json.schema"); if (schema.ValueKind != JsonValueKind.Object) return ""; var arrays = FindArrays(schema, "", 0).Take(2).ToArray(); return arrays.Length == 1 ? arrays[0] : ""; static IEnumerable FindArrays(JsonElement current, string path, int depth) { if (Text(current, "type") == "array") { yield return path; yield break; } var properties = MdpApiPullPlan.Value(current, "properties"); if (depth >= 5 || properties.ValueKind != JsonValueKind.Object) yield break; foreach (var property in properties.EnumerateObject()) { if (property.Name.Length == 0 || property.Name.Contains('.')) continue; var child = path.Length == 0 ? property.Name : path + "." + property.Name; foreach (var array in FindArrays(property.Value, child, depth + 1)) yield return array; } } } private static MdpApiPullPlan Postman(JsonElement root, string? selection) { var candidates = new List(); Walk(root); var selected = Choose(candidates, entry => Text(entry, "name") ?? "", selection); var request = MdpApiPullPlan.Value(selected, "request"); if (request.ValueKind == JsonValueKind.Undefined) request = selected; var uri = Text(request, "url") ?? Text(request, "url.raw"); var method = Text(request, "method"); if (uri is null || method is null) throw new MdpApiPullException("PULL_IMPORT_INVALID"); var plan = Build(uri, method); var example = Text(First(MdpApiPullPlan.Value(selected, "response")), "body"); var dataPath = ""; if (example is not null) { try { using var sample = JsonDocument.Parse(example); dataPath = new[] { "data.list", "data.items", "data", "items", "orders", "records" } .FirstOrDefault(name => MdpApiPullPlan.Value(sample.RootElement, name).ValueKind == JsonValueKind.Array) ?? ""; } catch (JsonException) { /* The operator chooses a path for incomplete examples. */ } } return plan with { Auth = AuthKind(Text(request, "auth.type")), ResponsePath = dataPath }; void Walk(JsonElement item) { if (MdpApiPullPlan.Value(item, "request").ValueKind == JsonValueKind.Object || MdpApiPullPlan.Value(item, "method").ValueKind == JsonValueKind.String) candidates.Add(item); var children = MdpApiPullPlan.Value(item, "item"); if (children.ValueKind == JsonValueKind.Array) foreach (var child in children.EnumerateArray()) Walk(child); } } private static T Choose(List candidates, Func name, string? selection) { var matches = candidates.Where(candidate => selection is null || name(candidate) == selection).Take(2).ToArray(); return matches.Length == 1 ? matches[0] : throw new MdpApiPullException(matches.Length > 1 ? "PULL_IMPORT_SELECT_OPERATION" : "PULL_IMPORT_INVALID"); } private static MdpApiPullPlan Curl(string text) { var args = Token.Matches(text.Replace("\\\r\n", "").Replace("\\\n", "")) .Select(match => match.Groups.Cast().Skip(1).First(group => group.Success).Value).ToArray(); if (args.Length < 2 || args[0] != "curl") throw new MdpApiPullException("PULL_IMPORT_INVALID"); var method = "GET"; var auth = "none"; var index = 1; string? url = null; for (; index < args.Length; index++) { var current = args[index]; if (current is "-X" or "--request") method = Arg(); else if (current == "--url") url = Arg(); else if (current is "-u" or "--user") { Arg(); auth = "basic"; } else if (current is "-d" or "--data" or "--data-raw" or "--data-binary" or "--json") { Arg(); method = "POST"; } else if (current is "-H" or "--header") { var header = Arg().Split(':', 2)[0].Trim(); if (header is "X-API-Key" or "Api-Key") auth = "apiKey"; } else if (Uri.TryCreate(current, UriKind.Absolute, out var endpoint) && endpoint.Scheme is "http" or "https" && url is null) url = current; else if (current is not ("-s" or "-S" or "--silent" or "--show-error")) throw new MdpApiPullException("PULL_IMPORT_UNSUPPORTED_OPTION"); } return Build(url ?? "", method) with { Auth = auth }; string Arg() => ++index < args.Length ? args[index] : throw new MdpApiPullException("PULL_IMPORT_INVALID"); } private static MdpApiPullPlan Build(string url, string method) { if (!Uri.TryCreate(url, UriKind.Absolute, out var endpoint) || endpoint.Scheme != "https" || endpoint.UserInfo.Length != 0 || method.ToUpperInvariant() is not ("GET" or "POST") || url.Contains('{') || url.Contains('}')) throw new MdpApiPullException("PULL_IMPORT_INVALID"); var clean = new UriBuilder(endpoint) { Query = "", Fragment = "" }.Uri.AbsoluteUri; return new MdpApiPullPlan(clean, method.ToUpperInvariant(), Mode: "single"); } private static string AuthKind(string? type) => type?.ToLowerInvariant() switch { "oauth2" => "oauth2", "basic" => "basic", "apikey" => "apiKey", _ => "none" }; private static JsonElement First(JsonElement array) => array.ValueKind == JsonValueKind.Array && array.GetArrayLength() > 0 ? array[0] : default; private static string? Text(JsonElement node, string path) => MdpApiPullPlan.Value(node, path) is { ValueKind: JsonValueKind.String } entry ? entry.GetString() : null; }