alef-e2e 0.4.1

Fixture-driven e2e test generator for alef
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
//! C# e2e test generator using xUnit.
//!
//! Generates `e2e/csharp/E2eTests.csproj` and `tests/{Category}Tests.cs`
//! files from JSON fixtures, driven entirely by `E2eConfig` and `CallConfig`.

use crate::config::E2eConfig;
use crate::escape::{escape_csharp, sanitize_filename};
use crate::field_access::FieldResolver;
use crate::fixture::{Assertion, Fixture, FixtureGroup};
use alef_core::backend::GeneratedFile;
use alef_core::config::AlefConfig;
use anyhow::Result;
use heck::ToUpperCamelCase;
use std::collections::HashMap;
use std::fmt::Write as FmtWrite;
use std::path::PathBuf;

use super::E2eCodegen;

/// C# e2e code generator.
pub struct CSharpCodegen;

impl E2eCodegen for CSharpCodegen {
    fn generate(
        &self,
        groups: &[FixtureGroup],
        e2e_config: &E2eConfig,
        alef_config: &AlefConfig,
    ) -> Result<Vec<GeneratedFile>> {
        let lang = self.language_name();
        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);

        let mut files = Vec::new();

        // Resolve call config with overrides.
        let call = &e2e_config.call;
        let overrides = call.overrides.get(lang);
        let function_name = overrides
            .and_then(|o| o.function.as_ref())
            .cloned()
            .unwrap_or_else(|| call.function.to_upper_camel_case());
        let class_name = overrides
            .and_then(|o| o.class.as_ref())
            .cloned()
            .unwrap_or_else(|| format!("{}Lib", alef_config.crate_config.name.to_upper_camel_case()));
        // The exception class is always {CrateName}Exception, generated by the C# backend.
        let exception_class = format!("{}Exception", alef_config.crate_config.name.to_upper_camel_case());
        let namespace = overrides.and_then(|o| o.module.as_ref()).cloned().unwrap_or_else(|| {
            if call.module.is_empty() {
                "Kreuzberg".to_string()
            } else {
                call.module.to_upper_camel_case()
            }
        });
        let result_is_simple = overrides.is_some_and(|o| o.result_is_simple);
        let result_var = &call.result_var;
        let is_async = call.r#async;

        // Resolve package config.
        let cs_pkg = e2e_config.resolve_package("csharp");
        let pkg_name = cs_pkg
            .as_ref()
            .and_then(|p| p.name.as_ref())
            .cloned()
            .unwrap_or_else(|| alef_config.crate_config.name.to_upper_camel_case());
        // The project reference path uses the crate name (with hyphens) for the directory
        // and the PascalCase name for the .csproj file.
        let pkg_path = cs_pkg
            .as_ref()
            .and_then(|p| p.path.as_ref())
            .cloned()
            .unwrap_or_else(|| {
                let dir_name = &alef_config.crate_config.name;
                format!("../../packages/csharp/{dir_name}/{pkg_name}.csproj")
            });
        let pkg_version = cs_pkg
            .as_ref()
            .and_then(|p| p.version.as_ref())
            .cloned()
            .unwrap_or_else(|| "0.1.0".to_string());

        // Generate the .csproj using a unique name derived from the package name so
        // it does not conflict with any hand-written project files in the same directory.
        let csproj_name = format!("{pkg_name}.E2eTests.csproj");
        files.push(GeneratedFile {
            path: output_base.join(&csproj_name),
            content: render_csproj(&pkg_name, &pkg_path, &pkg_version, e2e_config.dep_mode),
            generated_header: false,
        });

        // Generate test files per category.
        let tests_base = output_base.join("tests");
        let field_resolver = FieldResolver::new(
            &e2e_config.fields,
            &e2e_config.fields_optional,
            &e2e_config.result_fields,
            &e2e_config.fields_array,
        );

        // Resolve enum_fields from C# override config.
        static EMPTY_ENUM_FIELDS: std::sync::LazyLock<HashMap<String, String>> = std::sync::LazyLock::new(HashMap::new);
        let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&EMPTY_ENUM_FIELDS);

        for group in groups {
            let active: Vec<&Fixture> = group
                .fixtures
                .iter()
                .filter(|f| f.skip.as_ref().is_none_or(|s| !s.should_skip(lang)))
                .collect();

            if active.is_empty() {
                continue;
            }

            let test_class = format!("{}Tests", sanitize_filename(&group.category).to_upper_camel_case());
            let filename = format!("{test_class}.cs");
            let content = render_test_file(
                &group.category,
                &active,
                &namespace,
                &class_name,
                &function_name,
                &exception_class,
                result_var,
                &test_class,
                &e2e_config.call.args,
                &field_resolver,
                result_is_simple,
                is_async,
                e2e_config,
                enum_fields,
            );
            files.push(GeneratedFile {
                path: tests_base.join(filename),
                content,
                generated_header: true,
            });
        }

        Ok(files)
    }

    fn language_name(&self) -> &'static str {
        "csharp"
    }
}

// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------

fn render_csproj(pkg_name: &str, pkg_path: &str, pkg_version: &str, dep_mode: crate::config::DependencyMode) -> String {
    let pkg_ref = match dep_mode {
        crate::config::DependencyMode::Registry => {
            format!("    <PackageReference Include=\"{pkg_name}\" Version=\"{pkg_version}\" />")
        }
        crate::config::DependencyMode::Local => {
            format!("    <ProjectReference Include=\"{pkg_path}\" />")
        }
    };
    format!(
        r#"<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <IsPackable>false</IsPackable>
    <IsTestProject>true</IsTestProject>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
    <PackageReference Include="xunit" Version="2.9.3" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
  </ItemGroup>

  <ItemGroup>
{pkg_ref}
  </ItemGroup>
</Project>
"#
    )
}

#[allow(clippy::too_many_arguments)]
fn render_test_file(
    category: &str,
    fixtures: &[&Fixture],
    namespace: &str,
    class_name: &str,
    function_name: &str,
    exception_class: &str,
    result_var: &str,
    test_class: &str,
    args: &[crate::config::ArgMapping],
    field_resolver: &FieldResolver,
    result_is_simple: bool,
    is_async: bool,
    e2e_config: &E2eConfig,
    enum_fields: &HashMap<String, String>,
) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "// This file is auto-generated by alef. DO NOT EDIT.");
    // Always import System.Text.Json for the shared JsonOptions field.
    let _ = writeln!(out, "using System.Text.Json;");
    let _ = writeln!(out, "using System.Text.Json.Serialization;");
    let _ = writeln!(out, "using System.Threading.Tasks;");
    let _ = writeln!(out, "using Xunit;");
    let _ = writeln!(out, "using {namespace};");
    let _ = writeln!(out);
    let _ = writeln!(out, "namespace Kreuzberg.E2e;");
    let _ = writeln!(out);
    let _ = writeln!(out, "/// <summary>E2e tests for category: {category}.</summary>");
    let _ = writeln!(out, "public class {test_class}");
    let _ = writeln!(out, "{{");
    // Shared options used when deserializing config JSON in test setup.
    // Mirrors the options used by the library to ensure enum values round-trip correctly.
    let _ = writeln!(
        out,
        "    private static readonly JsonSerializerOptions ConfigOptions = new() {{ Converters = {{ new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower) }}, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault }};"
    );
    let _ = writeln!(out);

    for (i, fixture) in fixtures.iter().enumerate() {
        render_test_method(
            &mut out,
            fixture,
            class_name,
            function_name,
            exception_class,
            result_var,
            args,
            field_resolver,
            result_is_simple,
            is_async,
            e2e_config,
            enum_fields,
        );
        if i + 1 < fixtures.len() {
            let _ = writeln!(out);
        }
    }

    let _ = writeln!(out, "}}");
    out
}

#[allow(clippy::too_many_arguments)]
fn render_test_method(
    out: &mut String,
    fixture: &Fixture,
    class_name: &str,
    function_name: &str,
    exception_class: &str,
    result_var: &str,
    args: &[crate::config::ArgMapping],
    field_resolver: &FieldResolver,
    result_is_simple: bool,
    is_async: bool,
    e2e_config: &E2eConfig,
    enum_fields: &HashMap<String, String>,
) {
    let method_name = fixture.id.to_upper_camel_case();
    let description = &fixture.description;
    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");

    let (setup_lines, args_str) =
        build_args_and_setup(&fixture.input, args, class_name, e2e_config, enum_fields, &fixture.id);

    let return_type = if is_async { "async Task" } else { "void" };
    let await_kw = if is_async { "await " } else { "" };

    let _ = writeln!(out, "    [Fact]");
    let _ = writeln!(out, "    public {return_type} Test_{method_name}()");
    let _ = writeln!(out, "    {{");
    let _ = writeln!(out, "        // {description}");

    for line in &setup_lines {
        let _ = writeln!(out, "        {line}");
    }

    if expects_error {
        if is_async {
            let _ = writeln!(
                out,
                "        await Assert.ThrowsAsync<{exception_class}>(() => {class_name}.{function_name}({args_str}));"
            );
        } else {
            let _ = writeln!(
                out,
                "        Assert.Throws<{exception_class}>(() => {class_name}.{function_name}({args_str}));"
            );
        }
        let _ = writeln!(out, "    }}");
        return;
    }

    let _ = writeln!(
        out,
        "        var {result_var} = {await_kw}{class_name}.{function_name}({args_str});"
    );

    for assertion in &fixture.assertions {
        render_assertion(out, assertion, result_var, field_resolver, result_is_simple);
    }

    let _ = writeln!(out, "    }}");
}

/// Build setup lines (e.g. handle creation) and the argument list for the function call.
///
/// Returns `(setup_lines, args_string)`.
fn build_args_and_setup(
    input: &serde_json::Value,
    args: &[crate::config::ArgMapping],
    class_name: &str,
    e2e_config: &E2eConfig,
    enum_fields: &HashMap<String, String>,
    fixture_id: &str,
) -> (Vec<String>, String) {
    if args.is_empty() {
        return (Vec::new(), json_to_csharp(input));
    }

    let overrides = e2e_config.call.overrides.get("csharp");
    let options_type = overrides.and_then(|o| o.options_type.as_deref());

    let mut setup_lines: Vec<String> = Vec::new();
    let mut parts: Vec<String> = Vec::new();

    for arg in args {
        if arg.arg_type == "mock_url" {
            setup_lines.push(format!(
                "var {} = Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\";",
                arg.name,
            ));
            parts.push(arg.name.clone());
            continue;
        }

        if arg.arg_type == "handle" {
            // Generate a CreateEngine (or equivalent) call and pass the variable.
            let constructor_name = format!("Create{}", arg.name.to_upper_camel_case());
            let config_value = input.get(&arg.field).unwrap_or(&serde_json::Value::Null);
            if config_value.is_null()
                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
            {
                setup_lines.push(format!("var {} = {class_name}.{constructor_name}(null);", arg.name,));
            } else {
                // Sort discriminator fields ("type") to appear first in nested objects so
                // System.Text.Json [JsonPolymorphic] can find the type discriminator before
                // reading other properties (a requirement as of .NET 8).
                let sorted = sort_discriminator_first(config_value.clone());
                let json_str = serde_json::to_string(&sorted).unwrap_or_default();
                let name = &arg.name;
                setup_lines.push(format!(
                    "var {name}Config = JsonSerializer.Deserialize<CrawlConfig>(\"{}\", ConfigOptions)!;",
                    escape_csharp(&json_str),
                ));
                setup_lines.push(format!(
                    "var {} = {class_name}.{constructor_name}({name}Config);",
                    arg.name,
                    name = name,
                ));
            }
            parts.push(arg.name.clone());
            continue;
        }

        let val = input.get(&arg.field);
        match val {
            None | Some(serde_json::Value::Null) if arg.optional => {
                // Optional arg with no fixture value: pass null explicitly since
                // C# nullable parameters still require an argument at the call site.
                parts.push("null".to_string());
                continue;
            }
            None | Some(serde_json::Value::Null) => {
                // Required arg with no fixture value: pass a language-appropriate default.
                let default_val = match arg.arg_type.as_str() {
                    "string" => "\"\"".to_string(),
                    "int" | "integer" => "0".to_string(),
                    "float" | "number" => "0.0d".to_string(),
                    "bool" | "boolean" => "false".to_string(),
                    _ => "null".to_string(),
                };
                parts.push(default_val);
            }
            Some(v) => {
                // For json_object args with options_type, construct a typed C# object.
                if let (Some(opts_type), "json_object") = (options_type, arg.arg_type.as_str()) {
                    if let Some(obj) = v.as_object() {
                        let props: Vec<String> = obj
                            .iter()
                            .map(|(k, vv)| {
                                let pascal_key = k.to_upper_camel_case();
                                // Check if this field maps to an enum type.
                                let cs_val = if let Some(enum_type) = enum_fields.get(k) {
                                    // Map string value to enum constant (PascalCase).
                                    if let Some(s) = vv.as_str() {
                                        let pascal_val = s.to_upper_camel_case();
                                        format!("{enum_type}.{pascal_val}")
                                    } else {
                                        json_to_csharp(vv)
                                    }
                                } else {
                                    json_to_csharp(vv)
                                };
                                format!("{pascal_key} = {cs_val}")
                            })
                            .collect();
                        parts.push(format!("new {opts_type} {{ {} }}", props.join(", ")));
                        continue;
                    }
                }
                parts.push(json_to_csharp(v));
            }
        }
    }

    (setup_lines, parts.join(", "))
}

fn render_assertion(
    out: &mut String,
    assertion: &Assertion,
    result_var: &str,
    field_resolver: &FieldResolver,
    result_is_simple: bool,
) {
    // Skip assertions on fields that don't exist on the result type.
    if let Some(f) = &assertion.field {
        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
            let _ = writeln!(out, "        // skipped: field '{f}' not available on result type");
            return;
        }
    }

    let field_expr = if result_is_simple {
        result_var.to_string()
    } else {
        match &assertion.field {
            Some(f) if !f.is_empty() => field_resolver.accessor(f, "csharp", result_var),
            _ => result_var.to_string(),
        }
    };

    // Determine whether the field resolves to an optional (nullable) type in C#.
    let field_is_optional = assertion
        .field
        .as_deref()
        .map(|f| field_resolver.is_optional(field_resolver.resolve(f)))
        .unwrap_or(false);

    match assertion.assertion_type.as_str() {
        "equals" => {
            if let Some(expected) = &assertion.value {
                let cs_val = json_to_csharp(expected);
                // Only call .Trim() on string fields, not numeric or boolean ones.
                if expected.is_string() {
                    let _ = writeln!(out, "        Assert.Equal({cs_val}, {field_expr}.Trim());");
                } else if expected.is_number() && field_is_optional {
                    // Nullable numeric fields require an explicit cast of the expected
                    // literal so that C# can resolve the overload (e.g. ulong?).
                    let _ = writeln!(out, "        Assert.Equal((object?){cs_val}, (object?){field_expr});");
                } else {
                    let _ = writeln!(out, "        Assert.Equal({cs_val}, {field_expr});");
                }
            }
        }
        "contains" => {
            if let Some(expected) = &assertion.value {
                // Lowercase both expected and actual so that enum fields (where .ToString()
                // returns the PascalCase C# member name like "Anchor") correctly match
                // fixture snake_case values like "anchor".  String fields are unaffected
                // because lowercasing both sides preserves substring matches.
                let lower_expected = expected.as_str().map(|s| s.to_lowercase());
                let cs_val = lower_expected
                    .as_deref()
                    .map(|s| format!("\"{}\"", escape_csharp(s)))
                    .unwrap_or_else(|| json_to_csharp(expected));
                let _ = writeln!(
                    out,
                    "        Assert.Contains({cs_val}, {field_expr}.ToString().ToLower());"
                );
            }
        }
        "contains_all" => {
            if let Some(values) = &assertion.values {
                for val in values {
                    let lower_val = val.as_str().map(|s| s.to_lowercase());
                    let cs_val = lower_val
                        .as_deref()
                        .map(|s| format!("\"{}\"", escape_csharp(s)))
                        .unwrap_or_else(|| json_to_csharp(val));
                    let _ = writeln!(
                        out,
                        "        Assert.Contains({cs_val}, {field_expr}.ToString().ToLower());"
                    );
                }
            }
        }
        "not_contains" => {
            if let Some(expected) = &assertion.value {
                let cs_val = json_to_csharp(expected);
                let _ = writeln!(out, "        Assert.DoesNotContain({cs_val}, {field_expr}.ToString());");
            }
        }
        "not_empty" => {
            let _ = writeln!(
                out,
                "        Assert.False(string.IsNullOrEmpty({field_expr}?.ToString()));"
            );
        }
        "is_empty" => {
            let _ = writeln!(
                out,
                "        Assert.True(string.IsNullOrEmpty({field_expr}?.ToString()));"
            );
        }
        "contains_any" => {
            if let Some(values) = &assertion.values {
                let checks: Vec<String> = values
                    .iter()
                    .map(|v| {
                        let cs_val = json_to_csharp(v);
                        format!("{field_expr}.ToString().Contains({cs_val})")
                    })
                    .collect();
                let joined = checks.join(" || ");
                let _ = writeln!(
                    out,
                    "        Assert.True({joined}, \"expected to contain at least one of the specified values\");"
                );
            }
        }
        "greater_than" => {
            if let Some(val) = &assertion.value {
                let cs_val = json_to_csharp(val);
                let _ = writeln!(
                    out,
                    "        Assert.True({field_expr} > {cs_val}, \"expected > {cs_val}\");"
                );
            }
        }
        "less_than" => {
            if let Some(val) = &assertion.value {
                let cs_val = json_to_csharp(val);
                let _ = writeln!(
                    out,
                    "        Assert.True({field_expr} < {cs_val}, \"expected < {cs_val}\");"
                );
            }
        }
        "greater_than_or_equal" => {
            if let Some(val) = &assertion.value {
                let cs_val = json_to_csharp(val);
                let _ = writeln!(
                    out,
                    "        Assert.True({field_expr} >= {cs_val}, \"expected >= {cs_val}\");"
                );
            }
        }
        "less_than_or_equal" => {
            if let Some(val) = &assertion.value {
                let cs_val = json_to_csharp(val);
                let _ = writeln!(
                    out,
                    "        Assert.True({field_expr} <= {cs_val}, \"expected <= {cs_val}\");"
                );
            }
        }
        "starts_with" => {
            if let Some(expected) = &assertion.value {
                let cs_val = json_to_csharp(expected);
                let _ = writeln!(out, "        Assert.StartsWith({cs_val}, {field_expr});");
            }
        }
        "ends_with" => {
            if let Some(expected) = &assertion.value {
                let cs_val = json_to_csharp(expected);
                let _ = writeln!(out, "        Assert.EndsWith({cs_val}, {field_expr});");
            }
        }
        "min_length" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    let _ = writeln!(
                        out,
                        "        Assert.True({field_expr}.Length >= {n}, \"expected length >= {n}\");"
                    );
                }
            }
        }
        "max_length" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    let _ = writeln!(
                        out,
                        "        Assert.True({field_expr}.Length <= {n}, \"expected length <= {n}\");"
                    );
                }
            }
        }
        "count_min" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    let _ = writeln!(
                        out,
                        "        Assert.True({field_expr}.Count >= {n}, \"expected at least {n} elements\");"
                    );
                }
            }
        }
        "not_error" => {
            // Already handled by the call succeeding without exception.
        }
        "error" => {
            // Handled at the test method level.
        }
        other => {
            let _ = writeln!(out, "        // TODO: unsupported assertion type: {other}");
        }
    }
}

/// Recursively sort JSON objects so that any key named `"type"` appears first.
///
/// System.Text.Json's `[JsonPolymorphic]` requires the type discriminator to be
/// the first property when deserializing polymorphic types. Fixture config values
/// serialised via serde_json preserve insertion/alphabetical order, which may put
/// `"type"` after other keys (e.g. `"password"` before `"type"` in auth configs).
fn sort_discriminator_first(value: serde_json::Value) -> serde_json::Value {
    match value {
        serde_json::Value::Object(map) => {
            let mut sorted = serde_json::Map::with_capacity(map.len());
            // Insert "type" first if present.
            if let Some(type_val) = map.get("type") {
                sorted.insert("type".to_string(), sort_discriminator_first(type_val.clone()));
            }
            for (k, v) in map {
                if k != "type" {
                    sorted.insert(k, sort_discriminator_first(v));
                }
            }
            serde_json::Value::Object(sorted)
        }
        serde_json::Value::Array(arr) => {
            serde_json::Value::Array(arr.into_iter().map(sort_discriminator_first).collect())
        }
        other => other,
    }
}

/// Convert a `serde_json::Value` to a C# literal string.
fn json_to_csharp(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(s) => format!("\"{}\"", escape_csharp(s)),
        serde_json::Value::Bool(true) => "true".to_string(),
        serde_json::Value::Bool(false) => "false".to_string(),
        serde_json::Value::Number(n) => {
            if n.is_f64() {
                format!("{}d", n)
            } else {
                n.to_string()
            }
        }
        serde_json::Value::Null => "null".to_string(),
        serde_json::Value::Array(arr) => {
            let items: Vec<String> = arr.iter().map(json_to_csharp).collect();
            format!("new[] {{ {} }}", items.join(", "))
        }
        serde_json::Value::Object(_) => {
            let json_str = serde_json::to_string(value).unwrap_or_default();
            format!("\"{}\"", escape_csharp(&json_str))
        }
    }
}