alef-e2e 0.15.10

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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
//! Dart e2e test generator using package:test and package:http.
//!
//! Generates `e2e/dart/test/<category>_test.dart` files from JSON fixtures.
//! HTTP fixtures hit the mock server at `MOCK_SERVER_URL/fixtures/<id>`.
//! Non-HTTP fixtures without a dart-specific call override emit a skip stub.

use crate::codegen::resolve_field;
use crate::config::E2eConfig;
use crate::escape::sanitize_filename;
use crate::fixture::{Fixture, FixtureGroup, HttpFixture, ValidationErrorExpectation};
use alef_core::backend::GeneratedFile;
use alef_core::config::ResolvedCrateConfig;
use alef_core::hash::{self, CommentStyle};
use alef_core::template_versions::pub_dev;
use anyhow::Result;
use std::cell::Cell;
use std::fmt::Write as FmtWrite;
use std::path::PathBuf;

use super::E2eCodegen;
use super::client;

/// Dart e2e code generator.
pub struct DartE2eCodegen;

impl E2eCodegen for DartE2eCodegen {
    fn generate(
        &self,
        groups: &[FixtureGroup],
        e2e_config: &E2eConfig,
        config: &ResolvedCrateConfig,
    ) -> 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 package config.
        let dart_pkg = e2e_config.resolve_package("dart");
        let pkg_name = dart_pkg
            .as_ref()
            .and_then(|p| p.name.as_ref())
            .cloned()
            .unwrap_or_else(|| config.dart_pubspec_name());
        let pkg_path = dart_pkg
            .as_ref()
            .and_then(|p| p.path.as_ref())
            .cloned()
            .unwrap_or_else(|| "../../packages/dart".to_string());
        let pkg_version = dart_pkg
            .as_ref()
            .and_then(|p| p.version.as_ref())
            .cloned()
            .or_else(|| config.resolved_version())
            .unwrap_or_else(|| "0.1.0".to_string());

        // Generate pubspec.yaml with http dependency for HTTP client tests.
        files.push(GeneratedFile {
            path: output_base.join("pubspec.yaml"),
            content: render_pubspec(&pkg_name, &pkg_path, &pkg_version, e2e_config.dep_mode),
            generated_header: false,
        });

        // Generate dart_test.yaml to limit parallelism — the mock server uses keep-alive
        // connections and gets overwhelmed when test files run in parallel.
        files.push(GeneratedFile {
            path: output_base.join("dart_test.yaml"),
            content: concat!(
                "# Generated by alef — DO NOT EDIT.\n",
                "# Run test files sequentially to avoid overwhelming the mock server with\n",
                "# concurrent keep-alive connections.\n",
                "concurrency: 1\n",
            )
            .to_string(),
            generated_header: false,
        });

        let test_base = output_base.join("test");

        // One test file per fixture group.
        for group in groups {
            let active: Vec<&Fixture> = group
                .fixtures
                .iter()
                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
                .collect();

            if active.is_empty() {
                continue;
            }

            let filename = format!("{}_test.dart", sanitize_filename(&group.category));
            let content = render_test_file(&group.category, &active, e2e_config, lang);
            files.push(GeneratedFile {
                path: test_base.join(filename),
                content,
                generated_header: true,
            });
        }

        Ok(files)
    }

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

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

fn render_pubspec(
    pkg_name: &str,
    pkg_path: &str,
    pkg_version: &str,
    dep_mode: crate::config::DependencyMode,
) -> String {
    let test_ver = pub_dev::TEST_PACKAGE;
    let http_ver = pub_dev::HTTP_PACKAGE;

    let dep_block = match dep_mode {
        crate::config::DependencyMode::Registry => {
            format!("  {pkg_name}: ^{pkg_version}")
        }
        crate::config::DependencyMode::Local => {
            format!("  {pkg_name}:\n    path: {pkg_path}")
        }
    };

    format!(
        r#"name: e2e_dart
version: 0.1.0
publish_to: none

environment:
  sdk: ">=3.0.0 <4.0.0"

dependencies:
{dep_block}

dev_dependencies:
  test: {test_ver}
  http: {http_ver}
"#
    )
}

fn render_test_file(category: &str, fixtures: &[&Fixture], e2e_config: &E2eConfig, lang: &str) -> String {
    let mut out = String::new();
    out.push_str(&hash::header(CommentStyle::DoubleSlash));

    // Check if any fixture needs the http package (HTTP server tests).
    let has_http_fixtures = fixtures.iter().any(|f| f.is_http_test());

    // Check if any fixture needs Uint8List.fromList (batch item byte arrays).
    let has_batch_byte_items = fixtures.iter().any(|f| {
        let call_config = e2e_config.resolve_call(f.call.as_deref());
        call_config.args.iter().any(|a| {
            a.element_type.as_deref() == Some("BatchBytesItem") && resolve_field(&f.input, &a.field).is_array()
        })
    });

    // Detect whether any fixture uses file_path or bytes args — if so, setUpAll must chdir
    // to the test_documents directory so that relative paths like "docx/fake.docx" resolve.
    // Mirrors the Ruby/Python conftest and Swift setUp patterns.
    let needs_chdir = fixtures.iter().any(|f| {
        if f.is_http_test() {
            return false;
        }
        let call_config = e2e_config.resolve_call(f.call.as_deref());
        call_config
            .args
            .iter()
            .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
    });

    let _ = writeln!(out, "import 'package:test/test.dart';");
    let _ = writeln!(out, "import 'dart:io';");
    if has_batch_byte_items {
        let _ = writeln!(out, "import 'dart:typed_data';");
    }
    let _ = writeln!(out, "import 'package:kreuzberg/kreuzberg.dart';");
    // RustLib is the flutter_rust_bridge entrypoint; must be initialized before any FRB call.
    // It lives in the FRB-generated frb_generated.dart inside kreuzberg_bridge_generated/.
    let _ = writeln!(
        out,
        "import 'package:kreuzberg/src/kreuzberg_bridge_generated/frb_generated.dart' show RustLib;"
    );
    if has_http_fixtures {
        let _ = writeln!(out, "import 'dart:async';");
        let _ = writeln!(out, "import 'dart:convert';");
    }
    let _ = writeln!(out);

    // Emit file-level HTTP client and serialization mutex.
    //
    // The shared HttpClient reuses keep-alive connections to minimize TCP overhead.
    // The mutex (_lock) ensures requests are serialized within the file so the
    // connection pool is not exercised concurrently by dart:test's async runner.
    //
    // _withRetry wraps the entire request closure with one automatic retry on
    // transient connection errors (keep-alive connections can be silently closed
    // by the server just as the client tries to reuse them).
    if has_http_fixtures {
        let _ = writeln!(out, "HttpClient _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
        let _ = writeln!(out);
        let _ = writeln!(out, "var _lock = Future<void>.value();");
        let _ = writeln!(out);
        let _ = writeln!(out, "Future<T> _serialized<T>(Future<T> Function() fn) async {{");
        let _ = writeln!(out, "  final current = _lock;");
        let _ = writeln!(out, "  final next = Completer<void>();");
        let _ = writeln!(out, "  _lock = next.future;");
        let _ = writeln!(out, "  try {{");
        let _ = writeln!(out, "    await current;");
        let _ = writeln!(out, "    return await fn();");
        let _ = writeln!(out, "  }} finally {{");
        let _ = writeln!(out, "    next.complete();");
        let _ = writeln!(out, "  }}");
        let _ = writeln!(out, "}}");
        let _ = writeln!(out);
        // The `fn` here should be the full request closure — on socket failure we
        // recreate the HttpClient (drops old pooled connections) and retry once.
        let _ = writeln!(out, "Future<T> _withRetry<T>(Future<T> Function() fn) async {{");
        let _ = writeln!(out, "  try {{");
        let _ = writeln!(out, "    return await fn();");
        let _ = writeln!(out, "  }} on SocketException {{");
        let _ = writeln!(out, "    _httpClient.close(force: true);");
        let _ = writeln!(out, "    _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
        let _ = writeln!(out, "    return fn();");
        let _ = writeln!(out, "  }} on HttpException {{");
        let _ = writeln!(out, "    _httpClient.close(force: true);");
        let _ = writeln!(out, "    _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
        let _ = writeln!(out, "    return fn();");
        let _ = writeln!(out, "  }}");
        let _ = writeln!(out, "}}");
        let _ = writeln!(out);
    }

    let _ = writeln!(out, "// E2e tests for category: {category}");
    let _ = writeln!(out, "void main() {{");

    // Emit setUpAll to initialize the flutter_rust_bridge before any test runs and,
    // when fixtures load files by path, chdir to test_documents so that relative
    // paths like "docx/fake.docx" resolve correctly.
    //
    // The test_documents directory lives two levels above e2e/dart/ (at the repo root).
    // The FIXTURES_DIR environment variable can override this for CI environments.
    let _ = writeln!(out, "  setUpAll(() async {{");
    let _ = writeln!(out, "    await RustLib.init();");
    if needs_chdir {
        let _ = writeln!(
            out,
            "    final _testDocs = Platform.environment['FIXTURES_DIR'] ?? '../../test_documents';"
        );
        let _ = writeln!(out, "    final _dir = Directory(_testDocs);");
        let _ = writeln!(out, "    if (_dir.existsSync()) Directory.current = _dir;");
    }
    let _ = writeln!(out, "  }});");
    let _ = writeln!(out);

    // Close the shared client after all tests in this file complete.
    if has_http_fixtures {
        let _ = writeln!(out, "  tearDownAll(() => _httpClient.close());");
        let _ = writeln!(out);
    }

    for fixture in fixtures {
        render_test_case(&mut out, fixture, e2e_config, lang);
    }

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

fn render_test_case(out: &mut String, fixture: &Fixture, e2e_config: &E2eConfig, lang: &str) {
    // HTTP fixtures: hit the mock server.
    if let Some(http) = &fixture.http {
        render_http_test_case(out, fixture, http);
        return;
    }

    // Non-HTTP fixtures: render a call-based test using the resolved call config.
    let call_config = e2e_config.resolve_call(fixture.call.as_deref());
    let call_overrides = call_config.overrides.get(lang);
    let mut function_name = call_overrides
        .and_then(|o| o.function.as_ref())
        .cloned()
        .unwrap_or_else(|| call_config.function.clone());
    // Convert snake_case function names to camelCase for Dart conventions.
    function_name = function_name
        .split('_')
        .enumerate()
        .map(|(i, part)| {
            if i == 0 {
                part.to_string()
            } else {
                let mut chars = part.chars();
                match chars.next() {
                    None => String::new(),
                    Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                }
            }
        })
        .collect::<Vec<_>>()
        .join("");
    let result_var = &call_config.result_var;
    let description = escape_dart(&fixture.description);
    // `is_async` retained for future use (e.g. non-FRB backends); unused with FRB since
    // all wrappers return Future<T>.
    let _is_async = call_overrides.and_then(|o| o.r#async).unwrap_or(call_config.r#async);

    // Build argument list from fixture.input and call_config.args.
    // Use `resolve_field` (respects the `field` path like "input.data") rather than
    // looking up by `arg_def.name` directly — the name and the field key may differ.
    //
    // For `extract_file_sync` / `extract_file` fixtures that omit `mime_type`,
    // derive the MIME from the path extension so `extractBytesSync`/`extractBytes`
    // can be called (both require an explicit MIME type).
    let file_path_for_mime: Option<&str> = call_config
        .args
        .iter()
        .find(|a| a.arg_type == "file_path")
        .and_then(|a| resolve_field(&fixture.input, &a.field).as_str());

    // Detect whether this call converts a file_path arg to bytes at test-run time.
    // Dart cannot pass OS-level file paths through the FRB bridge — the idiomatic API
    // is always bytes. When a file_path arg is present (and no caller-supplied dart
    // function override has already been applied), remap the function name:
    //   extractFile      → extractBytes
    //   extractFileSync  → extractBytesSync
    let has_file_path_arg = call_config.args.iter().any(|a| a.arg_type == "file_path");
    // Apply the remap only when no per-fixture dart override has already specified the
    // function — if the fixture author set a dart-specific function name we trust it.
    let caller_supplied_override = call_overrides.and_then(|o| o.function.as_ref()).is_some();
    if has_file_path_arg && !caller_supplied_override {
        function_name = match function_name.as_str() {
            "extractFile" => "extractBytes".to_string(),
            "extractFileSync" => "extractBytesSync".to_string(),
            other => other.to_string(),
        };
    }

    let mut args = Vec::new();
    for arg_def in &call_config.args {
        let arg_value = resolve_field(&fixture.input, &arg_def.field);
        match arg_def.arg_type.as_str() {
            "bytes" | "file_path" => {
                // `bytes`: value is a file path string; load file contents at test-run time.
                // `file_path`: also loaded as bytes for dart — extractBytes/extractBytesSync is
                // the idiomatic Dart API since the Dart runtime cannot pass OS-level file paths
                // through the FFI bridge.
                if let serde_json::Value::String(file_path) = arg_value {
                    args.push(format!("File('{}').readAsBytesSync()", file_path));
                }
            }
            "string" => {
                match arg_value {
                    serde_json::Value::String(s) => {
                        args.push(format!("'{}'", escape_dart(s)));
                    }
                    serde_json::Value::Null
                        if arg_def.optional
                        // Optional string absent from fixture — try to infer MIME from path
                        // when the arg name looks like a MIME-type parameter.
                        && arg_def.name == "mime_type" =>
                    {
                        let inferred = file_path_for_mime
                            .and_then(mime_from_extension)
                            .unwrap_or("application/octet-stream");
                        args.push(format!("'{inferred}'"));
                    }
                    // Other optional strings with null value are omitted.
                    _ => {}
                }
            }
            "json_object" => {
                // Handle batch item arrays (BatchBytesItem / BatchFileItem).
                if let Some(elem_type) = &arg_def.element_type {
                    if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && arg_value.is_array() {
                        let dart_items = emit_dart_batch_item_array(arg_value, elem_type);
                        args.push(dart_items);
                    }
                } else if arg_def.name == "config" {
                    if let serde_json::Value::Object(map) = &arg_value {
                        // Fixture provides config overrides — build an ExtractionConfig constructor
                        // with defaults, overriding only the fields present in the fixture JSON.
                        // This handles error-triggering configs like {force_ocr:true, disable_ocr:true}.
                        if !map.is_empty() {
                            args.push(emit_extraction_config_dart(map));
                        }
                    }
                    // If config is null/absent, the wrapper supplies the default ExtractionConfig.
                }
            }
            _ => {}
        }
    }

    // All KreuzbergBridge methods return Future<T> because FRB v2 wraps every Rust
    // function as async in Dart — even "sync" Rust functions. Always emit an async
    // test body and await the call so the test framework waits for the future.
    let _ = writeln!(out, "  test('{description}', () async {{");

    // Emit the receiver class name and arguments
    let args_str = args.join(", ");
    let receiver_class = call_overrides
        .and_then(|o| o.class.as_ref())
        .cloned()
        .unwrap_or_else(|| "KreuzbergBridge".to_string());

    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");

    if expects_error {
        // flutter_rust_bridge 2.x decodes Rust errors as raw String values (not Exception
        // subtypes), so throwsException will not match. Use throwsA(anything) which matches
        // any thrown object regardless of type. Note: `anything` is a const Matcher value,
        // not a function — do not write `anything()` (Dart 3 / matcher-0.12.x compile error).
        let _ = writeln!(
            out,
            "    await expectLater({receiver_class}.{function_name}({args_str}), throwsA(anything));"
        );
    } else {
        let _ = writeln!(
            out,
            "    final {result_var} = await {receiver_class}.{function_name}({args_str});"
        );
    }

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

/// Converts a snake_case JSON key to Dart camelCase.
fn snake_to_camel(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut next_upper = false;
    for ch in s.chars() {
        if ch == '_' {
            next_upper = true;
        } else if next_upper {
            result.extend(ch.to_uppercase());
            next_upper = false;
        } else {
            result.push(ch);
        }
    }
    result
}

/// Emits a Dart `ExtractionConfig(...)` constructor with default values, overriding
/// fields present in `overrides` (from fixture JSON, snake_case keys).
///
/// Only simple scalar overrides (bool, int) are supported. Complex nested types
/// (ocr, chunking, etc.) are left at their defaults (null).
fn emit_extraction_config_dart(overrides: &serde_json::Map<String, serde_json::Value>) -> String {
    // Collect scalar overrides; convert keys to camelCase.
    let mut field_overrides: std::collections::HashMap<String, String> = std::collections::HashMap::new();
    for (key, val) in overrides {
        let camel = snake_to_camel(key);
        let dart_val = match val {
            serde_json::Value::Bool(b) => {
                if *b {
                    "true".to_string()
                } else {
                    "false".to_string()
                }
            }
            serde_json::Value::Number(n) => n.to_string(),
            serde_json::Value::String(s) => format!("'{s}'"),
            _ => continue, // skip complex nested objects
        };
        field_overrides.insert(camel, dart_val);
    }

    let use_cache = field_overrides.remove("useCache").unwrap_or_else(|| "true".to_string());
    let enable_quality_processing = field_overrides
        .remove("enableQualityProcessing")
        .unwrap_or_else(|| "true".to_string());
    let force_ocr = field_overrides
        .remove("forceOcr")
        .unwrap_or_else(|| "false".to_string());
    let disable_ocr = field_overrides
        .remove("disableOcr")
        .unwrap_or_else(|| "false".to_string());
    let include_document_structure = field_overrides
        .remove("includeDocumentStructure")
        .unwrap_or_else(|| "false".to_string());
    let max_archive_depth = field_overrides
        .remove("maxArchiveDepth")
        .unwrap_or_else(|| "3".to_string());

    format!(
        "ExtractionConfig(useCache: {use_cache}, enableQualityProcessing: {enable_quality_processing}, forceOcr: {force_ocr}, disableOcr: {disable_ocr}, resultFormat: ResultFormat.unified, outputFormat: OutputFormat.plain(), includeDocumentStructure: {include_document_structure}, maxArchiveDepth: {max_archive_depth})"
    )
}

// ---------------------------------------------------------------------------
// HTTP server test rendering — DartTestClientRenderer impl + thin driver wrapper
// ---------------------------------------------------------------------------

/// Renderer that emits `package:test` `test(...)` blocks using `dart:io HttpClient`
/// against the mock server (`Platform.environment['MOCK_SERVER_URL']`).
///
/// Skipped tests are emitted as self-contained stubs (complete test block with
/// `markTestSkipped`) entirely inside `render_test_open`. `render_test_close` uses
/// `in_skip` to emit the right closing token: nothing extra for skip stubs (already
/// closed) vs. `})));` for regular tests.
///
/// `is_redirect` must be set to `true` before invoking the shared driver for 3xx
/// fixtures so that `render_call` can inject `ioReq.followRedirects = false` after
/// the `openUrl` call.
struct DartTestClientRenderer {
    /// Set to `true` when `render_test_open` is called with a skip reason so that
    /// `render_test_close` can match the opening shape.
    in_skip: Cell<bool>,
    /// Pre-set to `true` by the thin wrapper when the fixture expects a 3xx response.
    /// `render_call` injects `ioReq.followRedirects = false` when this is `true`.
    is_redirect: Cell<bool>,
}

impl DartTestClientRenderer {
    fn new(is_redirect: bool) -> Self {
        Self {
            in_skip: Cell::new(false),
            is_redirect: Cell::new(is_redirect),
        }
    }
}

impl client::TestClientRenderer for DartTestClientRenderer {
    fn language_name(&self) -> &'static str {
        "dart"
    }

    /// Emit the test opening.
    ///
    /// For skipped fixtures: emit the entire self-contained stub (open + body +
    /// close + blank line) and set `in_skip = true` so `render_test_close` is a
    /// no-op.
    ///
    /// For active fixtures: emit `test('desc', () => _serialized(() => _withRetry(() async {`
    /// leaving the block open for the assertion primitives.
    fn render_test_open(&self, out: &mut String, _fn_name: &str, description: &str, skip_reason: Option<&str>) {
        let escaped_desc = escape_dart(description);
        if let Some(reason) = skip_reason {
            let escaped_reason = escape_dart(reason);
            let _ = writeln!(out, "  test('{escaped_desc}', () {{");
            let _ = writeln!(out, "    markTestSkipped('{escaped_reason}');");
            let _ = writeln!(out, "  }});");
            let _ = writeln!(out);
            self.in_skip.set(true);
        } else {
            let _ = writeln!(
                out,
                "  test('{escaped_desc}', () => _serialized(() => _withRetry(() async {{"
            );
            self.in_skip.set(false);
        }
    }

    /// Emit the test closing token.
    ///
    /// No-op for skip stubs (the stub was fully closed in `render_test_open`).
    /// Emits `})));` followed by a blank line for regular tests.
    fn render_test_close(&self, out: &mut String) {
        if self.in_skip.get() {
            // Stub was already closed in render_test_open.
            return;
        }
        let _ = writeln!(out, "  }})));");
        let _ = writeln!(out);
    }

    /// Emit the full `dart:io HttpClient` request scaffolding.
    ///
    /// Emits:
    /// - URL construction from `MOCK_SERVER_URL`.
    /// - `_httpClient.openUrl(method, uri)`.
    /// - `followRedirects = false` when `is_redirect` is pre-set on the renderer.
    /// - Content-Type header, request headers, cookies, optional body bytes.
    /// - `ioReq.close()` → `ioResp`.
    /// - Response-body drain into `bodyStr` (skipped for redirect responses).
    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
        // dart:io restricted headers (handled automatically by the HTTP stack).
        const DART_RESTRICTED_HEADERS: &[&str] = &["content-length", "host", "transfer-encoding"];

        let method = ctx.method.to_uppercase();
        let escaped_method = escape_dart(&method);

        // Fixture path is `/fixtures/<id>` — extract the id portion for URL construction.
        let fixture_path = escape_dart(ctx.path);

        // Determine effective content-type.
        let has_explicit_content_type = ctx.headers.keys().any(|k| k.to_lowercase() == "content-type");
        let effective_content_type = if has_explicit_content_type {
            ctx.headers
                .iter()
                .find(|(k, _)| k.to_lowercase() == "content-type")
                .map(|(_, v)| v.as_str())
                .unwrap_or("application/json")
        } else if ctx.body.is_some() {
            ctx.content_type.unwrap_or("application/json")
        } else {
            ""
        };

        let _ = writeln!(
            out,
            "    final baseUrl = Platform.environment['MOCK_SERVER_URL'] ?? 'http://localhost:8080';"
        );
        let _ = writeln!(out, "    final uri = Uri.parse('$baseUrl{fixture_path}');");
        let _ = writeln!(
            out,
            "    final ioReq = await _httpClient.openUrl('{escaped_method}', uri);"
        );

        // Disable automatic redirect following for 3xx fixtures so the test can
        // assert on the redirect status code itself.
        if self.is_redirect.get() {
            let _ = writeln!(out, "    ioReq.followRedirects = false;");
        }

        // Set content-type header.
        if !effective_content_type.is_empty() {
            let escaped_ct = escape_dart(effective_content_type);
            let _ = writeln!(out, "    ioReq.headers.set('content-type', '{escaped_ct}');");
        }

        // Set request headers (skip dart:io restricted headers and content-type, already handled).
        let mut header_pairs: Vec<(&String, &String)> = ctx.headers.iter().collect();
        header_pairs.sort_by_key(|(k, _)| k.as_str());
        for (name, value) in &header_pairs {
            if DART_RESTRICTED_HEADERS.contains(&name.to_lowercase().as_str()) {
                continue;
            }
            if name.to_lowercase() == "content-type" {
                continue; // Already handled above.
            }
            let escaped_name = escape_dart(&name.to_lowercase());
            let escaped_value = escape_dart(value);
            let _ = writeln!(out, "    ioReq.headers.set('{escaped_name}', '{escaped_value}');");
        }

        // Add cookies.
        if !ctx.cookies.is_empty() {
            let mut cookie_pairs: Vec<(&String, &String)> = ctx.cookies.iter().collect();
            cookie_pairs.sort_by_key(|(k, _)| k.as_str());
            let cookie_str: Vec<String> = cookie_pairs.iter().map(|(k, v)| format!("{k}={v}")).collect();
            let cookie_header = escape_dart(&cookie_str.join("; "));
            let _ = writeln!(out, "    ioReq.headers.set('cookie', '{cookie_header}');");
        }

        // Write body bytes if present (bypass charset-based encoding issues).
        if let Some(body) = ctx.body {
            let json_str = serde_json::to_string(body).unwrap_or_default();
            let escaped = escape_dart(&json_str);
            let _ = writeln!(out, "    final bodyBytes = utf8.encode('{escaped}');");
            let _ = writeln!(out, "    ioReq.add(bodyBytes);");
        }

        let _ = writeln!(out, "    final ioResp = await ioReq.close();");
        // Drain the response body to bind `bodyStr` for assertion primitives and to
        // allow the server to cleanly close the connection (prevents RST packets).
        // Redirect responses have no body to drain — skip to avoid a potential hang.
        if !self.is_redirect.get() {
            let _ = writeln!(out, "    final bodyStr = await ioResp.transform(utf8.decoder).join();");
        };
    }

    fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
        let _ = writeln!(
            out,
            "    expect(ioResp.statusCode, equals({status}), reason: 'status code mismatch');"
        );
    }

    /// Emit a single header assertion, handling special tokens `<<present>>`,
    /// `<<absent>>`, and `<<uuid>>`.
    fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
        let escaped_name = escape_dart(&name.to_lowercase());
        match expected {
            "<<present>>" => {
                let _ = writeln!(
                    out,
                    "    expect(ioResp.headers.value('{escaped_name}'), isNotNull, reason: 'header {escaped_name} should be present');"
                );
            }
            "<<absent>>" => {
                let _ = writeln!(
                    out,
                    "    expect(ioResp.headers.value('{escaped_name}'), isNull, reason: 'header {escaped_name} should be absent');"
                );
            }
            "<<uuid>>" => {
                let _ = writeln!(
                    out,
                    "    expect(ioResp.headers.value('{escaped_name}'), matches(RegExp(r'^[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}$')), reason: 'header {escaped_name} should be a UUID');"
                );
            }
            exact => {
                let escaped_value = escape_dart(exact);
                let _ = writeln!(
                    out,
                    "    expect(ioResp.headers.value('{escaped_name}'), contains('{escaped_value}'), reason: 'header {escaped_name} mismatch');"
                );
            }
        }
    }

    /// Emit an exact-equality body assertion.
    ///
    /// String bodies are compared as decoded text; structured JSON bodies are
    /// compared via `jsonDecode`.
    fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
        match expected {
            serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
                let json_str = serde_json::to_string(expected).unwrap_or_default();
                let escaped = escape_dart(&json_str);
                let _ = writeln!(out, "    final bodyJson = jsonDecode(bodyStr);");
                let _ = writeln!(out, "    final expectedJson = jsonDecode('{escaped}');");
                let _ = writeln!(
                    out,
                    "    expect(bodyJson, equals(expectedJson), reason: 'body mismatch');"
                );
            }
            serde_json::Value::String(s) => {
                let escaped = escape_dart(s);
                let _ = writeln!(
                    out,
                    "    expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
                );
            }
            other => {
                let escaped = escape_dart(&other.to_string());
                let _ = writeln!(
                    out,
                    "    expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
                );
            }
        }
    }

    /// Emit partial-body assertions — every key in `expected` must match the
    /// corresponding field in the parsed JSON response.
    fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
        let _ = writeln!(
            out,
            "    final partialJson = jsonDecode(bodyStr) as Map<String, dynamic>;"
        );
        if let Some(obj) = expected.as_object() {
            for (idx, (key, val)) in obj.iter().enumerate() {
                let escaped_key = escape_dart(key);
                let json_val = serde_json::to_string(val).unwrap_or_default();
                let escaped_val = escape_dart(&json_val);
                // Use an index-based variable name so keys with special characters
                // don't produce invalid Dart identifiers.
                let _ = writeln!(out, "    final _expectedField{idx} = jsonDecode('{escaped_val}');");
                let _ = writeln!(
                    out,
                    "    expect(partialJson['{escaped_key}'], equals(_expectedField{idx}), reason: 'partial body field \\'{escaped_key}\\' mismatch');"
                );
            }
        }
    }

    /// Emit validation-error assertions for 422 responses.
    fn render_assert_validation_errors(
        &self,
        out: &mut String,
        _response_var: &str,
        errors: &[ValidationErrorExpectation],
    ) {
        let _ = writeln!(out, "    final errBody = jsonDecode(bodyStr) as Map<String, dynamic>;");
        let _ = writeln!(out, "    final errList = (errBody['errors'] ?? []) as List<dynamic>;");
        for ve in errors {
            let loc_dart: Vec<String> = ve.loc.iter().map(|s| format!("'{}'", escape_dart(s))).collect();
            let loc_str = loc_dart.join(", ");
            let escaped_msg = escape_dart(&ve.msg);
            let _ = writeln!(
                out,
                "    expect(errList.any((e) => e is Map && (e['loc'] as List?)?.join(',') == [{loc_str}].join(',') && (e['msg'] as String? ?? '').contains('{escaped_msg}')), isTrue, reason: 'validation error not found: {escaped_msg}');"
            );
        }
    }
}

/// Render a `package:test` `test(...)` block for an HTTP server fixture.
///
/// Delegates to the shared [`client::http_call::render_http_test`] driver via
/// [`DartTestClientRenderer`]. HTTP 101 (WebSocket upgrade) fixtures are emitted
/// as skip stubs before reaching the driver because `dart:io HttpClient` cannot
/// handle protocol-switch responses.
fn render_http_test_case(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
    // HTTP 101 (WebSocket upgrade) — dart:io HttpClient cannot handle upgrade responses.
    if http.expected_response.status_code == 101 {
        let description = escape_dart(&fixture.description);
        let _ = writeln!(out, "  test('{description}', () {{");
        let _ = writeln!(
            out,
            "    markTestSkipped('Skipped: Dart HttpClient cannot handle 101 Switching Protocols responses');"
        );
        let _ = writeln!(out, "  }});");
        let _ = writeln!(out);
        return;
    }

    // Pre-set `is_redirect` on the renderer so `render_call` can inject
    // `ioReq.followRedirects = false` for 3xx fixtures. The shared driver has no
    // concept of expected status code so we thread it through renderer state.
    let is_redirect = http.expected_response.status_code / 100 == 3;
    client::http_call::render_http_test(out, &DartTestClientRenderer::new(is_redirect), fixture);
}

/// Infer a MIME type from a file path extension.
///
/// Returns `None` when the extension is unknown so the caller can supply a fallback.
/// Used in dart e2e tests when a fixture omits `mime_type` but uses a `file_path` arg.
fn mime_from_extension(path: &str) -> Option<&'static str> {
    let ext = path.rsplit('.').next()?;
    match ext.to_lowercase().as_str() {
        "docx" => Some("application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
        "xlsx" => Some("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
        "pptx" => Some("application/vnd.openxmlformats-officedocument.presentationml.presentation"),
        "pdf" => Some("application/pdf"),
        "txt" | "text" => Some("text/plain"),
        "html" | "htm" => Some("text/html"),
        "json" => Some("application/json"),
        "xml" => Some("application/xml"),
        "csv" => Some("text/csv"),
        "md" | "markdown" => Some("text/markdown"),
        "png" => Some("image/png"),
        "jpg" | "jpeg" => Some("image/jpeg"),
        "gif" => Some("image/gif"),
        "zip" => Some("application/zip"),
        "odt" => Some("application/vnd.oasis.opendocument.text"),
        "ods" => Some("application/vnd.oasis.opendocument.spreadsheet"),
        "odp" => Some("application/vnd.oasis.opendocument.presentation"),
        "rtf" => Some("application/rtf"),
        "epub" => Some("application/epub+zip"),
        "msg" => Some("application/vnd.ms-outlook"),
        "eml" => Some("message/rfc822"),
        _ => None,
    }
}

/// Emit Dart constructors for a batch item array (`BatchBytesItem` or `BatchFileItem`).
///
/// Returns a Dart list literal like:
/// ```dart
/// [BatchBytesItem(content: Uint8List.fromList([72, 101, ...]), mimeType: 'text/plain')]
/// ```
fn emit_dart_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
    let items: Vec<String> = arr
        .as_array()
        .map(|a| a.as_slice())
        .unwrap_or_default()
        .iter()
        .filter_map(|item| {
            let obj = item.as_object()?;
            match elem_type {
                "BatchBytesItem" => {
                    let content_bytes = obj
                        .get("content")
                        .and_then(|v| v.as_array())
                        .map(|arr| {
                            let nums: Vec<String> =
                                arr.iter().filter_map(|v| v.as_u64().map(|n| n.to_string())).collect();
                            format!("Uint8List.fromList([{}])", nums.join(", "))
                        })
                        .unwrap_or_else(|| "Uint8List(0)".to_string());
                    let mime_type = obj
                        .get("mime_type")
                        .and_then(|v| v.as_str())
                        .unwrap_or("application/octet-stream");
                    Some(format!(
                        "BatchBytesItem(content: {content_bytes}, mimeType: '{}')",
                        escape_dart(mime_type)
                    ))
                }
                "BatchFileItem" => {
                    let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
                    Some(format!("BatchFileItem(path: '{}')", escape_dart(path)))
                }
                _ => None,
            }
        })
        .collect();
    format!("[{}]", items.join(", "))
}

/// Escape a string for embedding in a Dart single-quoted string literal.
fn escape_dart(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('\'', "\\'")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
        .replace('\t', "\\t")
        .replace('$', "\\$")
}