Bundle: redb-route / redb.Route.JsonTransform (redb.Route.JsonTransform.txt), 9 files Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/redb.Route.JsonTransform/JsonTransformCompilationException.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.JsonTransform/JsonTransformCompilationException.cs ---- namespace redb.Route.JsonTransform; /// /// A JSONata specification could not be read or parsed. Raised while the route is compiled, so it /// surfaces from RouteContext.Start() with the specification's name and the engine's message /// (which carries the position of the error). /// public sealed class JsonTransformCompilationException : Exception { /// Creates the exception. public JsonTransformCompilationException(string specificationName, string message, Exception? inner = null) : base($"JSON transform '{specificationName}': {message}", inner) { SpecificationName = specificationName; } /// Specification name as given in the DSL / XML (file path, resource locator, or <inline>). public string SpecificationName { get; } } Path: redb-route/redb.Route.JsonTransform/JsonTransformDefinition.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.JsonTransform/JsonTransformDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; namespace redb.Route.JsonTransform; /// /// The <transformJson> node: applies a JSONata specification to the JSON body. The /// specification is compiled at route build — a missing file or a syntax error fails Start() /// with the specification name — and cached by source. Declarative on purpose: the XML form reads /// and . /// public sealed class JsonTransformDefinition : ProcessorDefinition { /// Creates the node. public JsonTransformDefinition(TextSource specification, JsonTransformOutput output = JsonTransformOutput.String) { Specification = specification ?? throw new ArgumentNullException(nameof(specification)); Output = output; } /// Where the JSONata text comes from. public TextSource Specification { get; } /// JSON text or a JsonNode tree. public JsonTransformOutput Output { get; } /// public override IProcessor CreateProcessor(IRouteContext context) { // Context services first (UseJsonTransform), then the DI container (AddJsonTransform), then defaults. var options = context.GetService() ?? context.GetServiceProvider()?.GetService(typeof(JsonTransformOptions)) as JsonTransformOptions ?? new JsonTransformOptions(); // Same lookup as the template step and the validator: context resolver, then base directory. // A miss stays a specification failure, not an IO one — the step promises one exception type. TextSource specification; try { specification = ResourceResolution.Locate(context, Specification, options.BaseDirectory, "JSONata specification"); } catch (FileNotFoundException ex) { throw new JsonTransformCompilationException(Specification.Name, ex.Message, ex); } var compiled = JsonTransformEngine.Compile(specification, options); return new JsonTransformProcessor(compiled, Output, options); } } Path: redb-route/redb.Route.JsonTransform/JsonTransformEngine.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.JsonTransform/JsonTransformEngine.cs ---- using System.Collections; using System.Collections.Concurrent; using System.Text.Json; using System.Text.Json.Nodes; using Jsonata.Net.Native; using Jsonata.Net.Native.Json; using StjBridge = Jsonata.Net.Native.SystemTextJson.JsonataExtensions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.JsonTransform; /// A parsed JSONata specification plus the source it came from. internal sealed record CompiledJsonTransform(TextSource Source, JsonataQuery Query); /// /// Compiles JSONata specifications once (cache keyed by source identity) and applies them per message. /// Input: the body as JSON text, bytes, a System.Text.Json tree, or a POCO (serialized camelCase). /// Bindings: $headers and $properties — the same names the payload templates use. /// internal static class JsonTransformEngine { private static readonly ConcurrentDictionary> Cache = new(StringComparer.Ordinal); private static readonly JsonSerializerOptions PocoOptions = new(JsonSerializerDefaults.Web); /// Drops every cached specification (tests). public static void ClearCache() => Cache.Clear(); public static CompiledJsonTransform Compile(TextSource source, JsonTransformOptions options) { // Keyed by the resolved file (path, size, write time): the cache is process-wide, and a relative // name alone would make two base directories share one specification. var key = source.ResolveCacheKey(options.BaseDirectory); var lazy = Cache.GetOrAdd(key, _ => new Lazy(() => Parse(source, options), LazyThreadSafetyMode.ExecutionAndPublication)); try { return lazy.Value; } catch { Cache.TryRemove(key, out _); // do not cache a failure throw; } } private static CompiledJsonTransform Parse(TextSource source, JsonTransformOptions options) { string text; try { text = source.Read(options.BaseDirectory); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) { throw new JsonTransformCompilationException(source.Name, ex.Message, ex); } try { return new CompiledJsonTransform(source, new JsonataQuery(text)); } catch (JsonataException ex) { throw new JsonTransformCompilationException(source.Name, ex.Message, ex); } } /// Applies the specification to the exchange body; null when the result is undefined. public static JToken? Run(CompiledJsonTransform compiled, IExchange exchange) { JToken input; try { input = ToJToken(exchange.In.Body); } catch (Exception ex) when (ex is JsonataException or Jsonata.Net.Native.Json.JsonParseException or System.Text.Json.JsonException or FormatException or ArgumentException or NotSupportedException) { throw new InvalidOperationException($"JSON transform '{compiled.Source.Name}': the body is not JSON ({ex.Message}).", ex); } var environment = new EvaluationEnvironment(); environment.BindValue("headers", StjBridge.FromObjectViaSystemTextJson(Sanitize(exchange.In.Headers), PocoOptions)); environment.BindValue("properties", StjBridge.FromObjectViaSystemTextJson(Sanitize(exchange.Properties), PocoOptions)); JToken result; try { result = compiled.Query.Eval(input, environment); } catch (JsonataException ex) { throw new InvalidOperationException($"JSON transform '{compiled.Source.Name}' failed: {ex.Message}", ex); } return result.Type == JTokenType.Undefined ? null : result; } private static JToken ToJToken(object? body) => body switch { null => JToken.Parse("null"), JToken token => token, string text => JToken.Parse(text), byte[] bytes => JToken.Parse(System.Text.Encoding.UTF8.GetString(bytes)), JsonNode node => StjBridge.FromSystemTextJson(node), JsonElement element => StjBridge.FromSystemTextJson(element), JsonDocument document => StjBridge.FromSystemTextJson(document), Stream stream => JToken.Parse(ReadStream(stream)), _ => StjBridge.FromObjectViaSystemTextJson(body, PocoOptions), }; /// Reads a stream body from its position and leaves it there (a later step may need it); the stream stays open — it belongs to the exchange. private static string ReadStream(Stream stream) { var position = stream.CanSeek ? stream.Position : -1; using var reader = new StreamReader(stream, System.Text.Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 4096, leaveOpen: true); var text = reader.ReadToEnd(); if (position >= 0) stream.Position = position; return text; } /// /// Headers and properties may hold anything (streams, DI scopes under __redb_scope:*); the /// binding keeps JSON-friendly values as they are, recurses into dictionaries and lists, and /// falls back to ToString() for the rest. /// private static Dictionary Sanitize(IEnumerable> pairs) { var result = new Dictionary(StringComparer.Ordinal); foreach (var (key, value) in pairs) { if (key.StartsWith("__", StringComparison.Ordinal)) continue; result[key] = SanitizeValue(value, depth: 0); } return result; } private static object? SanitizeValue(object? value, int depth) => value switch { null => null, string or bool or sbyte or byte or short or ushort or int or uint or long or ulong or float or double or decimal => value, DateTime or DateTimeOffset or Guid or TimeSpan => value.ToString(), JsonNode node => node, _ when depth > 8 => value.ToString(), IDictionary dictionary => dictionary.Cast() .ToDictionary(e => e.Key?.ToString() ?? string.Empty, e => SanitizeValue(e.Value, depth + 1)), IEnumerable list => list.Cast().Select(v => SanitizeValue(v, depth + 1)).ToList(), _ => value.ToString(), }; } Path: redb-route/redb.Route.JsonTransform/JsonTransformOptions.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.JsonTransform/JsonTransformOptions.cs ---- namespace redb.Route.JsonTransform; /// What TransformJson leaves in the body. public enum JsonTransformOutput { /// JSON text (ContentType = application/json). Default. String, /// A System.Text.Json.Nodes.JsonNode tree, for further steps that navigate the result. Node, } /// /// Package-wide settings, registered with services.AddJsonTransform(...) or /// context.UseJsonTransform(...); defaults apply when neither was called. /// public sealed class JsonTransformOptions { /// Directory relative specification paths are resolved against. Default . public string BaseDirectory { get; set; } = AppContext.BaseDirectory; /// Indent the JSON text output. Default false. public bool Indent { get; set; } } Path: redb-route/redb.Route.JsonTransform/JsonTransformProcessor.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.JsonTransform/JsonTransformProcessor.cs ---- using Jsonata.Net.Native.SystemTextJson; using redb.Route.Abstractions; namespace redb.Route.JsonTransform; /// Runtime side of : applies the specification and writes the result to the body. internal sealed class JsonTransformProcessor : IProcessor { private readonly CompiledJsonTransform _compiled; private readonly JsonTransformOutput _output; private readonly JsonTransformOptions _options; public JsonTransformProcessor(CompiledJsonTransform compiled, JsonTransformOutput output, JsonTransformOptions options) { _compiled = compiled; _output = output; _options = options; } public Task Process(IExchange exchange, CancellationToken ct = default) { var result = JsonTransformEngine.Run(_compiled, exchange); // Whatever the input was, what leaves this step is JSON (or nothing): the content type says so // in every branch, so a stale application/xml from the input never travels with a JSON body. exchange.In.ContentType = "application/json"; if (result is null) { exchange.In.Body = null; return Task.CompletedTask; } // Two statements on purpose: in one conditional expression the string branch would be converted // to JsonNode through its implicit string conversion, and the text result would leave as a JsonValue. if (_output == JsonTransformOutput.Node) exchange.In.Body = JsonataExtensions.ToSystemTextJsonNode(result); else exchange.In.Body = _options.Indent ? result.ToIndentedString() : result.ToFlatString(); return Task.CompletedTask; } } Path: redb-route/redb.Route.JsonTransform/JsonTransformRouteDefinitionExtensions.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.JsonTransform/JsonTransformRouteDefinitionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.JsonTransform; /// /// DSL of the JSON transform step. A string argument is a locator (file relative to /// , or assembly:Name/path); an inline /// specification is TextSource.Inline("..."). /// /// /// .TransformJson("Transforms/order-to-shipment.jsonata") /// .TransformJson(TextSource.Inline("{ 'id': orderId, 'to': { 'city': address.city }, 'tenant': $headers.tenant }")) /// .TransformJson("Transforms/x.jsonata", JsonTransformOutput.Node) /// /// /// public static class JsonTransformRouteDefinitionExtensions { /// Applies the JSONata specification at to the JSON body. public static IRouteDefinition TransformJson(this IRouteDefinition route, string locator, JsonTransformOutput output = JsonTransformOutput.String) => TransformJson(route, TextSource.FromLocator(locator), output); /// Applies the JSONata specification to the JSON body. public static IRouteDefinition TransformJson(this IRouteDefinition route, TextSource specification, JsonTransformOutput output = JsonTransformOutput.String) { ArgumentNullException.ThrowIfNull(route); var definition = new JsonTransformDefinition(specification, output) { Parent = route }; route.Outputs.Add(definition); // the public tree API, identical to ProcessorDefinition.AddOutput return route; } /// DI registration: services.AddJsonTransform(o => o.BaseDirectory = "/etc/acme/transforms"). public static IServiceCollection AddJsonTransform(this IServiceCollection services, Action? configure = null) { ArgumentNullException.ThrowIfNull(services); var options = new JsonTransformOptions(); configure?.Invoke(options); services.TryAddSingleton(options); return services; } /// Registration on a context built without DI: context.UseJsonTransform(o => o.Indent = true). public static IRouteContext UseJsonTransform(this IRouteContext context, Action? configure = null) { ArgumentNullException.ThrowIfNull(context); var options = new JsonTransformOptions(); configure?.Invoke(options); context.AddService(typeof(JsonTransformOptions), options); return context; } } Path: redb-route/redb.Route.JsonTransform/JsonTransformXmlContribution.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.JsonTransform/JsonTransformXmlContribution.cs ---- using System.Xml.Linq; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.JsonTransform; /// /// The <transformJson> element: JSONata /// over the body, the specification either referenced by a locator (a path or /// assembly:Name/path) or inline as the element's content (CDATA welcome) — exactly one /// of the two. /// public sealed class JsonTransformXmlContribution : IXmlElementContribution { /// public string Name => "transformJson"; /// public XmlElementKind Kind => XmlElementKind.Step; /// public ElementSpec Spec => new(Name, Kind, [ new AttributeSpec("spec", AttributeType.String) { Resource = true }, // The format spells the values lowercase (string/node); parsing is case-insensitive. new AttributeSpec("output", AttributeType.Enum, EnumValues: ["string", "node"]), ], [], AllowsTextContent: true); /// public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context) { var locator = context.Attr(element, "spec"); var inline = Text(element); if ((locator is null) == (inline is null)) { context.AddError(element, " takes either the spec locator or inline JSONata content, not both."); return current; } var output = JsonTransformOutput.String; if (context.Attr(element, "output") is { } outputName && !Enum.TryParse(outputName, ignoreCase: true, out output)) { context.AddError(element, $"'{outputName}' is not a transform output ({string.Join(", ", Enum.GetNames())})."); return current; } return locator is not null ? current.TransformJson(locator, output) : current.TransformJson(TextSource.Inline(inline!), output); } /// public void Print(XElement element, XmlCodeWriter code) { var output = element.Attribute("output")?.Value is { } o ? $"JsonTransformOutput.{Enum.Parse(o, true)}" : null; var source = element.Attribute("spec")?.Value is { } locator ? XmlCodeWriter.Str(locator) : $"TextSource.Inline({XmlCodeWriter.Str(Text(element) ?? "")})"; code.Verb(element, "TransformJson", output is null ? [source] : [source, output]); } private static string? Text(XElement element) { var text = string.Concat(element.Nodes().OfType().Select(t => t.Value)); return string.IsNullOrWhiteSpace(text) ? null : text.Trim(); } } Path: redb-route/redb.Route.JsonTransform/README.md Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.JsonTransform/README.md ---- # redb.Route.JsonTransform > Documentation and articles: Declarative JSON-to-JSON transformation with [JSONata](https://jsonata.org/) — the analog of Camel's `jslt` / `jolt` / `jsonata` components — on the native .NET engine [Jsonata.Net.Native](https://github.com/mikhail-barg/jsonata.net.native) (no JavaScript, no JVM). Field-to-field mapping with renaming, nesting, array unwrapping and defaults, without writing a template for the whole document. ```csharp .TransformJson("Transforms/order-to-shipment.jsonata") // file, compiled once, cached .TransformJson(TextSource.Inline(""" { "id": orderId, "to": { "city": address.city }, "skus": items.sku, "tenant": $headers.tenant } """)) .TransformJson("Transforms/x.jsonata", JsonTransformOutput.Node) // JsonNode body instead of text ``` | Rule | Why | |---|---| | A `string` argument is a **locator** (a file path or `assembly:Name/Path/file.jsonata`); inline text is `TextSource.Inline("...")`. | A string never has to be guessed as "path or text" — the same rule as templates and the expression language. | | A relative path is looked up by the context's `IRouteResourceResolver` first, then by `JsonTransformOptions.BaseDirectory` (default `AppContext.BaseDirectory`). A miss names both places. | One lookup order for the whole framework; inside a `.tpkg` the specification lives in `resources/`, which only the package resolver knows about. | | Compiled at route build. | A missing file or a syntax error fails `Start()` with the specification name and the engine's message. | | Input: the body as JSON text, `byte[]`, `Stream`, a `System.Text.Json` tree, or a POCO (serialized camelCase). | The step sits naturally after `Unmarshal` or straight after an HTTP consumer. | | `$headers` and `$properties` are bound in the specification. | The same names the payload templates use. | | Output: JSON text with `ContentType = application/json` (default; `Indent` option), or a `JsonNode` (`JsonTransformOutput.Node`). | An undefined result leaves a `null` body. | Options: `services.AddJsonTransform(o => ...)` or `context.UseJsonTransform(o => ...)` — `BaseDirectory`, `Indent`. XML form ([redb.Route.Xml](../redb.Route.Xml/README.md)): `` or the specification as the element's text (CDATA); `output="string|node"`. Path: redb-route/redb.Route.JsonTransform/redb.Route.JsonTransform.csproj Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.JsonTransform/redb.Route.JsonTransform.csproj ---- redb.Route.JsonTransform Declarative JSON-to-JSON transformation for redb.Route (JSONata, native .NET engine): TransformJson("spec.jsonata") compiles once, applies per message; headers and properties bound as $headers / $properties. esb;messaging;json;jsonata;transform;redb README.md