Skip to main content

alef_e2e/codegen/
dart.rs

1//! Dart e2e test generator using package:test and package:http.
2//!
3//! Generates `e2e/dart/test/<category>_test.dart` files from JSON fixtures.
4//! HTTP fixtures hit the mock server at `MOCK_SERVER_URL/fixtures/<id>`.
5//! Non-HTTP fixtures without a dart-specific call override emit a skip stub.
6
7use crate::codegen::resolve_field;
8use crate::config::E2eConfig;
9use crate::escape::sanitize_filename;
10use crate::field_access::FieldResolver;
11use crate::fixture::{Assertion, Fixture, FixtureGroup, HttpFixture, ValidationErrorExpectation};
12use alef_core::backend::GeneratedFile;
13use alef_core::config::ResolvedCrateConfig;
14use alef_core::hash::{self, CommentStyle};
15use alef_core::template_versions::pub_dev;
16use anyhow::Result;
17use heck::ToLowerCamelCase;
18use std::cell::Cell;
19use std::fmt::Write as FmtWrite;
20use std::path::PathBuf;
21
22use super::E2eCodegen;
23use super::client;
24
25/// Dart e2e code generator.
26pub struct DartE2eCodegen;
27
28impl E2eCodegen for DartE2eCodegen {
29    fn generate(
30        &self,
31        groups: &[FixtureGroup],
32        e2e_config: &E2eConfig,
33        config: &ResolvedCrateConfig,
34        _type_defs: &[alef_core::ir::TypeDef],
35        _enums: &[alef_core::ir::EnumDef],
36    ) -> Result<Vec<GeneratedFile>> {
37        let lang = self.language_name();
38        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
39
40        let mut files = Vec::new();
41
42        // Resolve package config.
43        let dart_pkg = e2e_config.resolve_package("dart");
44        let pkg_name = dart_pkg
45            .as_ref()
46            .and_then(|p| p.name.as_ref())
47            .cloned()
48            .unwrap_or_else(|| config.dart_pubspec_name());
49        let pkg_path = dart_pkg
50            .as_ref()
51            .and_then(|p| p.path.as_ref())
52            .cloned()
53            .unwrap_or_else(|| "../../packages/dart".to_string());
54        let pkg_version = dart_pkg
55            .as_ref()
56            .and_then(|p| p.version.as_ref())
57            .cloned()
58            .or_else(|| config.resolved_version())
59            .unwrap_or_else(|| "0.1.0".to_string());
60
61        // Generate pubspec.yaml with http dependency for HTTP client tests.
62        files.push(GeneratedFile {
63            path: output_base.join("pubspec.yaml"),
64            content: render_pubspec(&pkg_name, &pkg_path, &pkg_version, e2e_config.dep_mode),
65            generated_header: false,
66        });
67
68        // Generate dart_test.yaml to limit parallelism — the mock server uses keep-alive
69        // connections and gets overwhelmed when test files run in parallel.
70        files.push(GeneratedFile {
71            path: output_base.join("dart_test.yaml"),
72            content: concat!(
73                "# Generated by alef — DO NOT EDIT.\n",
74                "# Run test files sequentially to avoid overwhelming the mock server with\n",
75                "# concurrent keep-alive connections.\n",
76                "concurrency: 1\n",
77            )
78            .to_string(),
79            generated_header: false,
80        });
81
82        let test_base = output_base.join("test");
83
84        // One test file per fixture group.
85        let bridge_class = config.dart_bridge_class_name();
86
87        // FRB places its generated dart code under `lib/src/{module_name}_bridge_generated/`,
88        // where `module_name` is the snake_cased crate name (e.g. `html_to_markdown_rs`).
89        // This is independent of the pubspec `name` (which may be a short alias like `h2m`).
90        let frb_module_name = config.name.replace('-', "_");
91
92        // Methods declared as `stub_methods` in `[crates.dart]` cannot be bridged through
93        // FRB and have `unimplemented!()` bodies on the Rust side. Emitting e2e tests for
94        // these fixtures would result in `PanicException` at run-time. Filter them out
95        // here so the dart e2e suite mirrors the actual runtime surface of the binding.
96        let dart_stub_methods: std::collections::HashSet<String> = config
97            .dart
98            .as_ref()
99            .map(|d| d.stub_methods.iter().cloned().collect())
100            .unwrap_or_default();
101
102        for group in groups {
103            let active: Vec<&Fixture> = group
104                .fixtures
105                .iter()
106                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
107                .filter(|f| {
108                    let call_config = e2e_config.resolve_call_for_fixture(
109                        f.call.as_deref(),
110                        &f.id,
111                        &f.resolved_category(),
112                        &f.tags,
113                        &f.input,
114                    );
115                    let resolved_function = call_config
116                        .overrides
117                        .get(lang)
118                        .and_then(|o| o.function.as_ref())
119                        .cloned()
120                        .unwrap_or_else(|| call_config.function.clone());
121                    !dart_stub_methods.contains(&resolved_function)
122                })
123                .collect();
124
125            if active.is_empty() {
126                continue;
127            }
128
129            let filename = format!("{}_test.dart", sanitize_filename(&group.category));
130            let content = render_test_file(
131                &group.category,
132                &active,
133                e2e_config,
134                lang,
135                &pkg_name,
136                &frb_module_name,
137                &bridge_class,
138            );
139            files.push(GeneratedFile {
140                path: test_base.join(filename),
141                content,
142                generated_header: true,
143            });
144        }
145
146        Ok(files)
147    }
148
149    fn language_name(&self) -> &'static str {
150        "dart"
151    }
152}
153
154// ---------------------------------------------------------------------------
155// Rendering
156// ---------------------------------------------------------------------------
157
158fn render_pubspec(
159    pkg_name: &str,
160    pkg_path: &str,
161    pkg_version: &str,
162    dep_mode: crate::config::DependencyMode,
163) -> String {
164    let test_ver = pub_dev::TEST_PACKAGE;
165    let http_ver = pub_dev::HTTP_PACKAGE;
166
167    let dep_block = match dep_mode {
168        crate::config::DependencyMode::Registry => {
169            format!("  {pkg_name}: ^{pkg_version}")
170        }
171        crate::config::DependencyMode::Local => {
172            format!("  {pkg_name}:\n    path: {pkg_path}")
173        }
174    };
175
176    let sdk = alef_core::template_versions::toolchain::DART_SDK_CONSTRAINT;
177    format!(
178        r#"name: e2e_dart
179version: 0.1.0
180publish_to: none
181
182environment:
183  sdk: "{sdk}"
184
185dependencies:
186{dep_block}
187
188dev_dependencies:
189  test: {test_ver}
190  http: {http_ver}
191"#
192    )
193}
194
195fn render_test_file(
196    category: &str,
197    fixtures: &[&Fixture],
198    e2e_config: &E2eConfig,
199    lang: &str,
200    pkg_name: &str,
201    frb_module_name: &str,
202    bridge_class: &str,
203) -> String {
204    let mut out = String::new();
205    out.push_str(&hash::header(CommentStyle::DoubleSlash));
206    // Suppress unused_local_variable: `final result = await api.method(...)` is
207    // emitted for every test case; tests that only check for absence of errors
208    // do not consume `result`, triggering this dart-analyze warning.
209    out.push_str("// ignore_for_file: unused_local_variable\n\n");
210
211    // Check if any fixture needs the http package (HTTP server tests).
212    let has_http_fixtures = fixtures.iter().any(|f| f.is_http_test());
213
214    // Check if any fixture needs Uint8List.fromList (batch item byte arrays).
215    let has_batch_byte_items = fixtures.iter().any(|f| {
216        let call_config =
217            e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
218        call_config.args.iter().any(|a| {
219            a.element_type.as_deref() == Some("BatchBytesItem") && resolve_field(&f.input, &a.field).is_array()
220        })
221    });
222
223    // Detect whether any fixture uses file_path or bytes args — if so, setUpAll must chdir
224    // to the test_documents directory so that relative paths like "docx/fake.docx" resolve.
225    // Mirrors the Ruby/Python conftest and Swift setUp patterns.
226    let needs_chdir = fixtures.iter().any(|f| {
227        if f.is_http_test() {
228            return false;
229        }
230        let call_config =
231            e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
232        call_config
233            .args
234            .iter()
235            .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
236    });
237
238    // Detect whether any non-HTTP fixture uses a json_object arg that resolves to a JSON array —
239    // those are materialized via `jsonDecode` at test-run time and cast to `List<String>`.
240    // Handle args themselves no longer require `jsonDecode` since they construct the config via
241    // the FRB-generated `createCrawlConfigFromJson(json:)` helper which accepts the JSON string
242    // directly. The variable name is kept as `has_handle_args` for downstream stability.
243    let has_handle_args = fixtures.iter().any(|f| {
244        if f.is_http_test() {
245            return false;
246        }
247        let call_config =
248            e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
249        call_config
250            .args
251            .iter()
252            .any(|a| a.arg_type == "json_object" && super::resolve_field(&f.input, &a.field).is_array())
253    });
254
255    // Non-HTTP fixtures that build a mock-server URL still reference `Platform.environment`
256    // (from `dart:io`). This applies to `mock_url` args and to fixtures routed through a
257    // `client_factory` (per-call override or per-language override) that derives `_mockUrl`
258    // inline. Without this, the generated tests fail to compile with
259    // `Error: Undefined name 'Platform'`.
260    let lang_client_factory = e2e_config
261        .call
262        .overrides
263        .get(lang)
264        .and_then(|o| o.client_factory.as_deref())
265        .is_some();
266    let has_mock_url_refs = lang_client_factory
267        || fixtures.iter().any(|f| {
268            if f.is_http_test() {
269                return false;
270            }
271            let call_config = e2e_config.resolve_call_for_fixture(
272                f.call.as_deref(),
273                &f.id,
274                &f.resolved_category(),
275                &f.tags,
276                &f.input,
277            );
278            if call_config.args.iter().any(|a| a.arg_type == "mock_url") {
279                return true;
280            }
281            call_config
282                .overrides
283                .get(lang)
284                .and_then(|o| o.client_factory.as_deref())
285                .is_some()
286        });
287
288    let _ = writeln!(out, "import 'package:test/test.dart';");
289    // `dart:io` provides HttpClient/SocketException (HTTP fixtures), Platform/Directory
290    // (file-path/bytes fixtures requiring chdir), and Platform.environment (mock-url
291    // fixtures). Skip the import when none of these are in play — unconditional emission
292    // triggers `unused_import` warnings.
293    if has_http_fixtures || needs_chdir || has_mock_url_refs {
294        let _ = writeln!(out, "import 'dart:io';");
295    }
296    if has_batch_byte_items {
297        let _ = writeln!(out, "import 'dart:typed_data';");
298    }
299    let _ = writeln!(out, "import 'package:{pkg_name}/{pkg_name}.dart';");
300    // RustLib is the flutter_rust_bridge entrypoint; must be initialized before any FRB call.
301    // FRB places its generated dart sources under `lib/src/{module_name}_bridge_generated/`,
302    // where `module_name` is the snake_cased crate name (independent of the pubspec `name`,
303    // which may be a short alias like `h2m`). `RustLib` lives in `frb_generated.dart` and
304    // is not re-exported by the FRB barrel `lib.dart`, so we import it directly.
305    let _ = writeln!(
306        out,
307        "import 'package:{pkg_name}/src/{frb_module_name}_bridge_generated/frb_generated.dart' show RustLib;"
308    );
309    if has_http_fixtures {
310        let _ = writeln!(out, "import 'dart:async';");
311    }
312    // dart:convert provides jsonDecode for handle-arg engine construction and HTTP response parsing.
313    if has_http_fixtures || has_handle_args {
314        let _ = writeln!(out, "import 'dart:convert';");
315    }
316    let _ = writeln!(out);
317
318    // Emit file-level HTTP client and serialization mutex.
319    //
320    // The shared HttpClient reuses keep-alive connections to minimize TCP overhead.
321    // The mutex (_lock) ensures requests are serialized within the file so the
322    // connection pool is not exercised concurrently by dart:test's async runner.
323    //
324    // _withRetry wraps the entire request closure with one automatic retry on
325    // transient connection errors (keep-alive connections can be silently closed
326    // by the server just as the client tries to reuse them).
327    if has_http_fixtures {
328        let _ = writeln!(out, "HttpClient _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
329        let _ = writeln!(out);
330        let _ = writeln!(out, "var _lock = Future<void>.value();");
331        let _ = writeln!(out);
332        let _ = writeln!(out, "Future<T> _serialized<T>(Future<T> Function() fn) async {{");
333        let _ = writeln!(out, "  final current = _lock;");
334        let _ = writeln!(out, "  final next = Completer<void>();");
335        let _ = writeln!(out, "  _lock = next.future;");
336        let _ = writeln!(out, "  try {{");
337        let _ = writeln!(out, "    await current;");
338        let _ = writeln!(out, "    return await fn();");
339        let _ = writeln!(out, "  }} finally {{");
340        let _ = writeln!(out, "    next.complete();");
341        let _ = writeln!(out, "  }}");
342        let _ = writeln!(out, "}}");
343        let _ = writeln!(out);
344        // The `fn` here should be the full request closure — on socket failure we
345        // recreate the HttpClient (drops old pooled connections) and retry once.
346        let _ = writeln!(out, "Future<T> _withRetry<T>(Future<T> Function() fn) async {{");
347        let _ = writeln!(out, "  try {{");
348        let _ = writeln!(out, "    return await fn();");
349        let _ = writeln!(out, "  }} on SocketException {{");
350        let _ = writeln!(out, "    _httpClient.close(force: true);");
351        let _ = writeln!(out, "    _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
352        let _ = writeln!(out, "    return fn();");
353        let _ = writeln!(out, "  }} on HttpException {{");
354        let _ = writeln!(out, "    _httpClient.close(force: true);");
355        let _ = writeln!(out, "    _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
356        let _ = writeln!(out, "    return fn();");
357        let _ = writeln!(out, "  }}");
358        let _ = writeln!(out, "}}");
359        let _ = writeln!(out);
360    }
361
362    let _ = writeln!(out, "// E2e tests for category: {category}");
363    let _ = writeln!(out, "void main() {{");
364
365    // Emit setUpAll to initialize the flutter_rust_bridge before any test runs and,
366    // when fixtures load files by path, chdir to test_documents so that relative
367    // paths like "docx/fake.docx" resolve correctly.
368    //
369    // The test_documents directory lives two levels above e2e/dart/ (at the repo root).
370    // The FIXTURES_DIR environment variable can override this for CI environments.
371    let _ = writeln!(out, "  setUpAll(() async {{");
372    let _ = writeln!(out, "    await RustLib.init();");
373    if needs_chdir {
374        let test_docs_path = e2e_config.test_documents_relative_from(0);
375        let _ = writeln!(
376            out,
377            "    final _testDocs = Platform.environment['FIXTURES_DIR'] ?? '{test_docs_path}';"
378        );
379        let _ = writeln!(out, "    final _dir = Directory(_testDocs);");
380        let _ = writeln!(out, "    if (_dir.existsSync()) Directory.current = _dir;");
381    }
382    let _ = writeln!(out, "  }});");
383    let _ = writeln!(out);
384
385    // Close the shared client after all tests in this file complete.
386    if has_http_fixtures {
387        let _ = writeln!(out, "  tearDownAll(() => _httpClient.close());");
388        let _ = writeln!(out);
389    }
390
391    for fixture in fixtures {
392        render_test_case(&mut out, fixture, e2e_config, lang, bridge_class);
393    }
394
395    let _ = writeln!(out, "}}");
396    out
397}
398
399fn render_test_case(out: &mut String, fixture: &Fixture, e2e_config: &E2eConfig, lang: &str, bridge_class: &str) {
400    // HTTP fixtures: hit the mock server.
401    if let Some(http) = &fixture.http {
402        render_http_test_case(out, fixture, http);
403        return;
404    }
405
406    // Non-HTTP fixtures: render a call-based test using the resolved call config.
407    let call_config = e2e_config.resolve_call_for_fixture(
408        fixture.call.as_deref(),
409        &fixture.id,
410        &fixture.resolved_category(),
411        &fixture.tags,
412        &fixture.input,
413    );
414    // Build per-call field resolver using the effective field sets for this call.
415    let call_field_resolver = FieldResolver::new(
416        e2e_config.effective_fields(call_config),
417        e2e_config.effective_fields_optional(call_config),
418        e2e_config.effective_result_fields(call_config),
419        e2e_config.effective_fields_array(call_config),
420        e2e_config.effective_fields_method_calls(call_config),
421    );
422    let field_resolver = &call_field_resolver;
423    let call_overrides = call_config.overrides.get(lang);
424    let mut function_name = call_overrides
425        .and_then(|o| o.function.as_ref())
426        .cloned()
427        .unwrap_or_else(|| call_config.function.clone());
428    // Convert snake_case function names to camelCase for Dart conventions.
429    function_name = function_name
430        .split('_')
431        .enumerate()
432        .map(|(i, part)| {
433            if i == 0 {
434                part.to_string()
435            } else {
436                let mut chars = part.chars();
437                match chars.next() {
438                    None => String::new(),
439                    Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
440                }
441            }
442        })
443        .collect::<Vec<_>>()
444        .join("");
445    let result_var = &call_config.result_var;
446    let description = escape_dart(&fixture.description);
447    let fixture_id = &fixture.id;
448    // `is_async` retained for future use (e.g. non-FRB backends); unused with FRB since
449    // all wrappers return Future<T>.
450    let _is_async = call_overrides.and_then(|o| o.r#async).unwrap_or(call_config.r#async);
451
452    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
453    let is_streaming = crate::codegen::streaming_assertions::resolve_is_streaming(fixture, call_config.streaming);
454    // `result_is_simple = true` means the dart return is a scalar/bytes value
455    // (e.g. `Uint8List` for speech/file_content), not a struct. Field-based
456    // assertions like `audio.not_empty` collapse to whole-result checks so we
457    // don't emit `result.audio` against a `Uint8List` receiver.
458    let result_is_simple = call_overrides.is_some_and(|o| o.result_is_simple) || call_config.result_is_simple;
459
460    // Resolve options_type and options_via from per-fixture → per-call → default.
461    // These drive how `json_object` args are constructed:
462    //   options_via = "from_json" — call `createTypeNameFromJson(json: r'...')` bridge
463    //                               helper and pass the result as a named parameter `req:`.
464    //   All other values (or absent) — existing behaviour (batch arrays, config objects,
465    //   generic JSON arrays, or nothing).
466    let options_type: Option<&str> = call_overrides.and_then(|o| o.options_type.as_deref());
467    let options_via: &str = call_overrides
468        .and_then(|o| o.options_via.as_deref())
469        .unwrap_or("kwargs");
470
471    // Build argument list from fixture.input and call_config.args.
472    // Use `resolve_field` (respects the `field` path like "input.data") rather than
473    // looking up by `arg_def.name` directly — the name and the field key may differ.
474    //
475    // For `extract_file_sync` / `extract_file` fixtures that omit `mime_type`,
476    // derive the MIME from the path extension so `extractBytesSync`/`extractBytes`
477    // can be called (both require an explicit MIME type).
478    let file_path_for_mime: Option<&str> = call_config
479        .args
480        .iter()
481        .find(|a| a.arg_type == "file_path")
482        .and_then(|a| resolve_field(&fixture.input, &a.field).as_str());
483
484    // Detect whether this call converts a file_path arg to bytes at test-run time.
485    // Dart cannot pass OS-level file paths through the FRB bridge — the idiomatic API
486    // is always bytes. When a file_path arg is present (and no caller-supplied dart
487    // function override has already been applied), remap the function name:
488    //   extractFile      → extractBytes
489    //   extractFileSync  → extractBytesSync
490    let has_file_path_arg = call_config.args.iter().any(|a| a.arg_type == "file_path");
491    // Apply the remap only when no per-fixture dart override has already specified the
492    // function — if the fixture author set a dart-specific function name we trust it.
493    let caller_supplied_override = call_overrides.and_then(|o| o.function.as_ref()).is_some();
494    if has_file_path_arg && !caller_supplied_override {
495        function_name = match function_name.as_str() {
496            "extractFile" => "extractBytes".to_string(),
497            "extractFileSync" => "extractBytesSync".to_string(),
498            other => other.to_string(),
499        };
500    }
501
502    // setup_lines holds per-test statements that must precede the main call:
503    // engine construction (handle args) and URL building (mock_url args).
504    let mut setup_lines: Vec<String> = Vec::new();
505    let mut args = Vec::new();
506
507    for arg_def in &call_config.args {
508        match arg_def.arg_type.as_str() {
509            "mock_url" => {
510                let name = arg_def.name.clone();
511                if fixture.has_host_root_route() {
512                    let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
513                    setup_lines.push(format!(
514                        r#"final {name} = Platform.environment["{env_key}"] ?? (Platform.environment["MOCK_SERVER_URL"]! + "/fixtures/{fixture_id}");"#
515                    ));
516                } else {
517                    setup_lines.push(format!(
518                        r#"final {name} = "${{Platform.environment["MOCK_SERVER_URL"] ?? "http://localhost:8080"}}/fixtures/{fixture_id}";"#
519                    ));
520                }
521                args.push(name);
522                continue;
523            }
524            "handle" => {
525                let name = arg_def.name.clone();
526                let field = arg_def.field.strip_prefix("input.").unwrap_or(&arg_def.field);
527                let config_value = fixture.input.get(field).cloned().unwrap_or(serde_json::Value::Null);
528                // Derive the create-function name: "engine" → "createEngine".
529                let create_fn = {
530                    let mut chars = name.chars();
531                    let pascal = match chars.next() {
532                        None => String::new(),
533                        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
534                    };
535                    format!("create{pascal}")
536                };
537                if config_value.is_null()
538                    || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
539                {
540                    setup_lines.push(format!("final {name} = await {bridge_class}.{create_fn}();"));
541                } else {
542                    let json_str = serde_json::to_string(&config_value).unwrap_or_default();
543                    let config_var = format!("{name}Config");
544                    // FRB-generated free function: `createCrawlConfigFromJson(json: '...')` — async,
545                    // deserializes the JSON into the mirror struct via the Rust `create_<type>_from_json`
546                    // helper emitted by the dart backend. This avoids relying on a Dart-side `fromJson`
547                    // constructor (FRB classes don't expose one).
548                    setup_lines.push(format!(
549                        "final {config_var} = await createCrawlConfigFromJson(json: r'{json_str}');"
550                    ));
551                    // Facade exposes `createEngine` with a named `config:` parameter — call it that way.
552                    setup_lines.push(format!(
553                        "final {name} = await {bridge_class}.{create_fn}(config: {config_var});"
554                    ));
555                }
556                args.push(name);
557                continue;
558            }
559            _ => {}
560        }
561
562        let arg_value = resolve_field(&fixture.input, &arg_def.field);
563        match arg_def.arg_type.as_str() {
564            "bytes" | "file_path" => {
565                // `bytes`: value is a file path string; load file contents at test-run time.
566                // `file_path`: also loaded as bytes for dart — extractBytes/extractBytesSync is
567                // the idiomatic Dart API since the Dart runtime cannot pass OS-level file paths
568                // through the FFI bridge.
569                if let serde_json::Value::String(file_path) = arg_value {
570                    args.push(format!("File('{}').readAsBytesSync()", file_path));
571                }
572            }
573            "string" => {
574                // The alef-generated Dart facade (e.g. `KreuzbergBridge`) emits required
575                // params as positional and optional params inside a `{...}` named block
576                // (see alef-backend-dart/src/gen_bindings/functions.rs).  Mirror that
577                // calling convention here: required string args → positional literal;
578                // optional string args → `name: 'value'` named-argument syntax.
579                //
580                // Special case: when dart remaps `extractFile*` → `extractBytes*`
581                // (because dart cannot pass OS file paths through the FFI bridge), the
582                // wrapper requires `mime_type` positionally even though the source IR
583                // marks it as optional on `extractFile*`. Force positional in that case.
584                let dart_param_name = snake_to_camel(&arg_def.name);
585                let mime_required_due_to_remap = has_file_path_arg
586                    && arg_def.name == "mime_type"
587                    && (function_name == "extractBytes" || function_name == "extractBytesSync");
588                let use_positional = mime_required_due_to_remap || !arg_def.optional;
589                match arg_value {
590                    serde_json::Value::String(s) => {
591                        let literal = format!("'{}'", escape_dart(s));
592                        if use_positional {
593                            args.push(literal);
594                        } else {
595                            args.push(format!("{dart_param_name}: {literal}"));
596                        }
597                    }
598                    serde_json::Value::Null
599                        if arg_def.optional
600                        // Optional string absent from fixture — try to infer MIME from path
601                        // when the arg name looks like a MIME-type parameter.
602                        && arg_def.name == "mime_type" =>
603                    {
604                        let inferred = file_path_for_mime
605                            .and_then(mime_from_extension)
606                            .unwrap_or("application/octet-stream");
607                        if use_positional {
608                            args.push(format!("'{inferred}'"));
609                        } else {
610                            args.push(format!("{dart_param_name}: '{inferred}'"));
611                        }
612                    }
613                    // Other optional strings with null value are omitted.
614                    _ => {}
615                }
616            }
617            "json_object" => {
618                // Handle batch item arrays (BatchBytesItem / BatchFileItem).
619                if let Some(elem_type) = &arg_def.element_type {
620                    if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && arg_value.is_array() {
621                        let dart_items = emit_dart_batch_item_array(arg_value, elem_type);
622                        args.push(dart_items);
623                    } else if elem_type == "String" && arg_value.is_array() {
624                        // Scalar string array (e.g. `texts: ["a", "b"]` for embed_texts).
625                        // The `KreuzbergBridge` facade declares these parameters as required
626                        // positional (e.g. `embedTexts(List<String> texts, EmbeddingConfig config)`),
627                        // so the list literal must be passed positionally — matching the
628                        // facade contract rather than the underlying FRB bridge's named-arg
629                        // convention.
630                        let items: Vec<String> = arg_value
631                            .as_array()
632                            .unwrap()
633                            .iter()
634                            .filter_map(|v| v.as_str())
635                            .map(|s| format!("'{}'", escape_dart(s)))
636                            .collect();
637                        args.push(format!("<String>[{}]", items.join(", ")));
638                    }
639                } else if options_via == "from_json" {
640                    // `from_json` path: construct a typed mirror-struct via the generated
641                    // `create<TypeName>FromJson(json: '...')` bridge helper, then pass it
642                    // as the named FRB parameter `req: _var`.
643                    //
644                    // The helper is generated by `emit_from_json_fn` in the dart bridge-crate
645                    // generator and made available as a top-level function via the exported
646                    // `liter_llm_bridge_generated/lib.dart`. The parameter name used in the
647                    // bridge method call is always `req:` for single-request-object methods
648                    // (derived from the Rust IR param name).
649                    if let Some(opts_type) = options_type {
650                        if !arg_value.is_null() {
651                            let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
652                            // Escape for Dart single-quoted string literal (handles embedded quotes,
653                            // backslashes, and interpolation markers).
654                            let escaped_json = escape_dart(&json_str);
655                            let var_name = format!("_{}", arg_def.name);
656                            let dart_fn = type_name_to_create_from_json_dart(opts_type);
657                            setup_lines.push(format!("final {var_name} = await {dart_fn}(json: '{escaped_json}');"));
658                            // FRB bridge method param name is `req` for all single-request methods.
659                            // Use `req:` as the named argument label.
660                            args.push(format!("req: {var_name}"));
661                        }
662                    }
663                } else if arg_def.name == "config" {
664                    if let serde_json::Value::Object(map) = &arg_value {
665                        if !map.is_empty() {
666                            // When the call override specifies a non-default `options_type`
667                            // (e.g. `EmbeddingConfig` for `embed_texts`), or the override map
668                            // contains a non-scalar field that the literal `ExtractionConfig`
669                            // constructor cannot express (e.g. `output_format: "markdown"` is
670                            // a tagged enum, not a plain string), fall back to the
671                            // FRB-generated `create<Type>FromJson(json: '...')` helper which
672                            // round-trips the JSON through serde and so preserves enum tags,
673                            // nested configs, and string-valued enum variants verbatim.
674                            let explicit_options =
675                                options_type.is_some_and(|t| t != "ExtractionConfig" && t != "FileExtractionConfig");
676                            let has_non_scalar = map.values().any(|v| {
677                                matches!(
678                                    v,
679                                    serde_json::Value::String(_)
680                                        | serde_json::Value::Object(_)
681                                        | serde_json::Value::Array(_)
682                                )
683                            });
684                            if explicit_options || has_non_scalar {
685                                let opts_type = options_type.unwrap_or("ExtractionConfig");
686                                let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
687                                let escaped_json = escape_dart(&json_str);
688                                let var_name = format!("_{}", arg_def.name);
689                                let dart_fn = type_name_to_create_from_json_dart(opts_type);
690                                setup_lines
691                                    .push(format!("final {var_name} = await {dart_fn}(json: '{escaped_json}');"));
692                                args.push(var_name);
693                            } else {
694                                // Fixture provides scalar-only overrides — build an
695                                // `ExtractionConfig` constructor literal with defaults,
696                                // overriding only the bool/int fields present in the
697                                // fixture JSON. Handles configs such as
698                                // {force_ocr:true, disable_ocr:true} that toggle error paths.
699                                args.push(emit_extraction_config_dart(map));
700                            }
701                        }
702                    }
703                    // If config is null/absent, the wrapper supplies the default ExtractionConfig.
704                } else if arg_value.is_array() {
705                    // Generic JSON array (e.g. batch_urls: ["/page1", "/page2"]).
706                    // Decode via jsonDecode and cast to List<String> at test-run time.
707                    let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
708                    let var_name = arg_def.name.clone();
709                    setup_lines.push(format!(
710                        "final {var_name} = (jsonDecode(r'{json_str}') as List<dynamic>).cast<String>();"
711                    ));
712                    args.push(var_name);
713                } else if let serde_json::Value::Object(map) = &arg_value {
714                    // Generic options-style json_object arg (e.g. h2m's
715                    // `options: ConversionOptions` on `convert(html, options)`). When the
716                    // fixture provides input.options and the call config declares an
717                    // `options_type`, build the mirror struct via the FRB-generated
718                    // `create<OptionsType>FromJson(json: '...')` helper. Use the arg's
719                    // original name (e.g. `options`) as the named parameter label.
720                    //
721                    // When the fixture also carries a visitor spec, swap to the
722                    // `create<OptionsType>FromJsonWithVisitor(json, visitor)` helper
723                    // (emitted by `alef-backend-dart` for trait bridges with `type_alias`
724                    // + `options_field` binding). The `_visitor` variable is materialised
725                    // in the visitor block below — its setup line is inserted ahead of
726                    // this options call by `build_dart_visitor`.
727                    if !map.is_empty() {
728                        if let Some(opts_type) = options_type {
729                            let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
730                            let escaped_json = escape_dart(&json_str);
731                            let dart_param_name = snake_to_camel(&arg_def.name);
732                            let var_name = format!("_{}", arg_def.name);
733                            let dart_fn = type_name_to_create_from_json_dart(opts_type);
734                            if fixture.visitor.is_some() {
735                                setup_lines.push(format!(
736                                    "final {var_name} = await {dart_fn}WithVisitor(json: '{escaped_json}', visitor: _visitor);"
737                                ));
738                            } else {
739                                setup_lines
740                                    .push(format!("final {var_name} = await {dart_fn}(json: '{escaped_json}');"));
741                            }
742                            if arg_def.optional {
743                                args.push(format!("{dart_param_name}: {var_name}"));
744                            } else {
745                                args.push(var_name);
746                            }
747                        }
748                    }
749                }
750            }
751            _ => {}
752        }
753    }
754
755    // Fixture-driven visitor handle. When `fixture.visitor` is set we build a
756    // `_visitor` via the `createHtmlVisitor(...)` factory (emitted by
757    // `alef-backend-dart`'s trait-bridge generator in the `type_alias` mode)
758    // and thread it into the options blob via the
759    // `create<OptionsType>FromJsonWithVisitor(json, visitor)` helper (handled
760    // a few lines above in the json_object arg branch).
761    //
762    // The visitor setup line is INSERTED at the front of `setup_lines` so
763    // `_visitor` is defined before any `_options` line that references it.
764    // Fixtures without an `options` json_object in input still need an options
765    // blob to carry the visitor through to convert — we synthesise an empty-
766    // options call to `createConversionOptionsFromJsonWithVisitor(json: '{}',
767    // visitor: _visitor)` here when no `options` arg was emitted in the loop
768    // above.
769    if let Some(visitor_spec) = &fixture.visitor {
770        let mut visitor_setup: Vec<String> = Vec::new();
771        let _ = super::dart_visitors::build_dart_visitor(&mut visitor_setup, visitor_spec);
772        // Prepend the visitor block so `_visitor` is in scope by the time the
773        // options call (which may reference it) runs.
774        for line in visitor_setup.into_iter().rev() {
775            setup_lines.insert(0, line);
776        }
777
778        // If no `options` arg was emitted by the loop above (the fixture has no
779        // input.options block), build an empty options-with-visitor and add it as
780        // an `options:` named arg so the visitor reaches the convert call.
781        let already_has_options = args.iter().any(|a| a.starts_with("options:") || a == "_options");
782        if !already_has_options {
783            if let Some(opts_type) = options_type {
784                let dart_fn = type_name_to_create_from_json_dart(opts_type);
785                setup_lines.push(format!(
786                    "final _options = await {dart_fn}WithVisitor(json: '{{}}', visitor: _visitor);"
787                ));
788                args.push("options: _options".to_string());
789            }
790        }
791    }
792
793    // Resolve client_factory: when set, tests create a client instance and call
794    // methods on it rather than using static bridge-class calls. This mirrors the
795    // go/python/zig pattern for stateful clients (e.g. liter-llm).
796    let client_factory: Option<&str> = call_overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
797        e2e_config
798            .call
799            .overrides
800            .get(lang)
801            .and_then(|o| o.client_factory.as_deref())
802    });
803
804    // Convert factory name to camelCase (same rule as function_name above).
805    let client_factory_camel: Option<String> = client_factory.map(|f| {
806        f.split('_')
807            .enumerate()
808            .map(|(i, part)| {
809                if i == 0 {
810                    part.to_string()
811                } else {
812                    let mut chars = part.chars();
813                    match chars.next() {
814                        None => String::new(),
815                        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
816                    }
817                }
818            })
819            .collect::<Vec<_>>()
820            .join("")
821    });
822
823    // All bridge methods return Future<T> because FRB v2 wraps every Rust
824    // function as async in Dart — even "sync" Rust functions. Always emit an async
825    // test body and await the call so the test framework waits for the future.
826    let _ = writeln!(out, "  test('{description}', () async {{");
827
828    let args_str = args.join(", ");
829    let receiver_class = call_overrides
830        .and_then(|o| o.class.as_ref())
831        .cloned()
832        .unwrap_or_else(|| bridge_class.to_string());
833
834    // When client_factory is set, determine the mock URL and emit client instantiation.
835    // The mock URL derivation follows the same has_host_root_route / plain-fixture split
836    // used by the mock_url arg handler above.
837    let (receiver, extra_setup): (String, Option<String>) = if let Some(factory) = &client_factory_camel {
838        let has_mock_url = call_config.args.iter().any(|a| a.arg_type == "mock_url");
839        let mock_url_setup = if !has_mock_url {
840            // No explicit mock_url arg — derive the URL inline.
841            if fixture.has_host_root_route() {
842                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
843                Some(format!(
844                    "final _mockUrl = Platform.environment[\"{env_key}\"] ?? (Platform.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{fixture_id}\");"
845                ))
846            } else {
847                Some(format!(
848                    r#"final _mockUrl = "${{Platform.environment["MOCK_SERVER_URL"] ?? "http://localhost:8080"}}/fixtures/{fixture_id}";"#
849                ))
850            }
851        } else {
852            None
853        };
854        let url_expr = if has_mock_url {
855            // A mock_url arg was emitted into setup_lines already — reuse the variable name
856            // from the first mock_url arg definition so we don't duplicate the URL.
857            call_config
858                .args
859                .iter()
860                .find(|a| a.arg_type == "mock_url")
861                .map(|a| a.name.clone())
862                .unwrap_or_else(|| "_mockUrl".to_string())
863        } else {
864            "_mockUrl".to_string()
865        };
866        let create_line = format!("final _client = await {receiver_class}.{factory}('test-key', baseUrl: {url_expr});");
867        let full_setup = if let Some(url_line) = mock_url_setup {
868            Some(format!("{url_line}\n    {create_line}"))
869        } else {
870            Some(create_line)
871        };
872        ("_client".to_string(), full_setup)
873    } else {
874        (receiver_class.clone(), None)
875    };
876
877    if expects_error && (!setup_lines.is_empty() || extra_setup.is_some()) {
878        // Wrap setup + call in an async lambda so any exception at any step is caught.
879        // flutter_rust_bridge 2.x decodes Rust errors as raw String values (not Exception
880        // subtypes), so throwsException will not match. Use throwsA(anything) instead.
881        let _ = writeln!(out, "    await expectLater(() async {{");
882        for line in &setup_lines {
883            let _ = writeln!(out, "      {line}");
884        }
885        if let Some(extra) = &extra_setup {
886            for line in extra.lines() {
887                let _ = writeln!(out, "      {line}");
888            }
889        }
890        if is_streaming {
891            let _ = writeln!(out, "      return {receiver}.{function_name}({args_str}).toList();");
892        } else {
893            let _ = writeln!(out, "      return {receiver}.{function_name}({args_str});");
894        }
895        let _ = writeln!(out, "    }}(), throwsA(anything));");
896    } else if expects_error {
897        // No setup lines, direct call — same throwsA(anything) rationale as above.
898        if let Some(extra) = &extra_setup {
899            for line in extra.lines() {
900                let _ = writeln!(out, "    {line}");
901            }
902        }
903        if is_streaming {
904            let _ = writeln!(
905                out,
906                "    await expectLater({receiver}.{function_name}({args_str}).toList(), throwsA(anything));"
907            );
908        } else {
909            let _ = writeln!(
910                out,
911                "    await expectLater({receiver}.{function_name}({args_str}), throwsA(anything));"
912            );
913        }
914    } else {
915        for line in &setup_lines {
916            let _ = writeln!(out, "    {line}");
917        }
918        if let Some(extra) = &extra_setup {
919            for line in extra.lines() {
920                let _ = writeln!(out, "    {line}");
921            }
922        }
923        if is_streaming {
924            let _ = writeln!(
925                out,
926                "    final {result_var} = await {receiver}.{function_name}({args_str}).toList();"
927            );
928        } else {
929            let _ = writeln!(
930                out,
931                "    final {result_var} = await {receiver}.{function_name}({args_str});"
932            );
933        }
934        for assertion in &fixture.assertions {
935            if is_streaming {
936                render_streaming_assertion_dart(out, assertion, result_var);
937            } else {
938                render_assertion_dart(out, assertion, result_var, result_is_simple, field_resolver);
939            }
940        }
941    }
942
943    let _ = writeln!(out, "  }});");
944    let _ = writeln!(out);
945}
946
947/// Render `.length` / `?.length ?? 0` against a Dart field accessor.
948///
949/// Count-style assertions (`count_equals`, `count_min`, `min_length`, `max_length`)
950/// operate on collection-typed fields. FRB v2 maps `Option<Vec<T>>` to `List<T>?`
951/// (nullable) but `Vec<T>` to `List<T>` (non-null). Emitting `?.length ?? 0`
952/// against a non-null receiver triggers `invalid_null_aware_operator`. Inspect
953/// the IR via `FieldResolver::is_optional` and choose the safe form per field.
954fn dart_length_expr(field_accessor: &str, field: Option<&str>, field_resolver: &FieldResolver) -> String {
955    let is_optional = field
956        .map(|f| {
957            let resolved = field_resolver.resolve(f);
958            field_resolver.is_optional(f) || field_resolver.is_optional(resolved)
959        })
960        .unwrap_or(false);
961    if is_optional {
962        format!("{field_accessor}?.length ?? 0")
963    } else {
964        format!("{field_accessor}.length")
965    }
966}
967
968fn dart_format_value(val: &serde_json::Value) -> String {
969    match val {
970        serde_json::Value::String(s) => format!("'{}'", escape_dart(s)),
971        serde_json::Value::Bool(b) => b.to_string(),
972        serde_json::Value::Number(n) => n.to_string(),
973        serde_json::Value::Null => "null".to_string(),
974        other => format!("'{}'", escape_dart(&other.to_string())),
975    }
976}
977
978/// Render a single fixture assertion as a Dart `package:test` `expect(...)` call.
979///
980/// Field paths are converted per-segment to camelCase (FRB v2 convention) using
981/// [`field_to_dart_accessor`].  All 24 fixture assertion types are handled.
982///
983/// Assertions on fixture fields that are not in the configured `result_fields` set
984/// are emitted as a `// skipped:` comment instead — the Dart binding may model a
985/// different result shape than the fixture asserts on (e.g. flat `ScrapeResult` vs.
986/// nested `result.browser.*`), and emitting unresolvable getters would break the
987/// whole file at compile time.
988fn render_assertion_dart(
989    out: &mut String,
990    assertion: &Assertion,
991    result_var: &str,
992    result_is_simple: bool,
993    field_resolver: &FieldResolver,
994) {
995    // Skip assertions on fields that don't exist on the dart result type. This must run
996    // BEFORE the array-traversal and standard accessor paths since both emit code that
997    // references the field — an unknown field path produces an `isn't defined` error.
998    if !result_is_simple {
999        if let Some(f) = assertion.field.as_deref() {
1000            // Use the head segment (before any `[].`) for validation since `is_valid_for_result`
1001            // only checks the first path component.
1002            let head = f.split("[].").next().unwrap_or(f);
1003            if !head.is_empty() && !field_resolver.is_valid_for_result(head) {
1004                let _ = writeln!(out, "    // skipped: field '{f}' not available on dart result type");
1005                return;
1006            }
1007        }
1008    }
1009
1010    // Skip assertions that traverse a tagged-union variant boundary. FRB exposes
1011    // tagged unions like `FormatMetadata` as sealed classes whose variants are
1012    // accessed via pattern matching (`switch (m) { case FormatMetadata_Excel ... }`)
1013    // — there is no `.excel?` getter, so the fixture path cannot be expressed as
1014    // a simple chained accessor without language-specific pattern-matching codegen.
1015    if let Some(f) = assertion.field.as_deref() {
1016        if !f.is_empty() && field_resolver.tagged_union_split(f).is_some() {
1017            let _ = writeln!(
1018                out,
1019                "    // skipped: field '{f}' crosses a tagged-union variant boundary (not expressible in Dart)"
1020            );
1021            return;
1022        }
1023    }
1024
1025    // Handle array traversal (e.g. "links[].link_type" → any() expression).
1026    if let Some(f) = assertion.field.as_deref() {
1027        if let Some(dot) = f.find("[].") {
1028            // Apply the alias mapping to the full `xxx[].yyy` path first so renamed
1029            // sub-fields (e.g. `assets[].category` → `assets[].asset_category`) resolve
1030            // correctly. Split *after* resolving so both the array head and the element
1031            // path reflect any alias rewrites.
1032            let resolved_full = field_resolver.resolve(f);
1033            let (array_part, elem_part) = match resolved_full.find("[].") {
1034                Some(rdot) => (&resolved_full[..rdot], &resolved_full[rdot + 3..]),
1035                // Resolver mapped the path away from `[].` form — fall back to the original
1036                // split, since downstream code expects the array/elem structure.
1037                None => (&f[..dot], &f[dot + 3..]),
1038            };
1039            let array_accessor = if array_part.is_empty() {
1040                result_var.to_string()
1041            } else {
1042                field_resolver.accessor(array_part, "dart", result_var)
1043            };
1044            let elem_accessor = field_to_dart_accessor(elem_part);
1045            match assertion.assertion_type.as_str() {
1046                "contains" => {
1047                    if let Some(expected) = &assertion.value {
1048                        let dart_val = dart_format_value(expected);
1049                        let _ = writeln!(
1050                            out,
1051                            "    expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isTrue);"
1052                        );
1053                    }
1054                }
1055                "contains_all" => {
1056                    if let Some(values) = &assertion.values {
1057                        for val in values {
1058                            let dart_val = dart_format_value(val);
1059                            let _ = writeln!(
1060                                out,
1061                                "    expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isTrue);"
1062                            );
1063                        }
1064                    }
1065                }
1066                "not_contains" => {
1067                    if let Some(expected) = &assertion.value {
1068                        let dart_val = dart_format_value(expected);
1069                        let _ = writeln!(
1070                            out,
1071                            "    expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isFalse);"
1072                        );
1073                    } else if let Some(values) = &assertion.values {
1074                        for val in values {
1075                            let dart_val = dart_format_value(val);
1076                            let _ = writeln!(
1077                                out,
1078                                "    expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isFalse);"
1079                            );
1080                        }
1081                    }
1082                }
1083                "not_empty" => {
1084                    let _ = writeln!(
1085                        out,
1086                        "    expect({array_accessor}.any((e) => e.{elem_accessor}.toString().isNotEmpty), isTrue);"
1087                    );
1088                }
1089                other => {
1090                    let _ = writeln!(
1091                        out,
1092                        "    // skipped: unsupported traversal assertion '{other}' on '{f}'"
1093                    );
1094                }
1095            }
1096            return;
1097        }
1098    }
1099
1100    let field_accessor = if result_is_simple {
1101        // Whole-result assertion path: the dart return is a scalar (e.g. a
1102        // `Uint8List` for speech/file_content), so any `field` on the
1103        // assertion resolves to the whole value rather than a sub-accessor.
1104        result_var.to_string()
1105    } else {
1106        match assertion.field.as_deref() {
1107            // Use the shared accessor builder (`FieldResolver::accessor`) — it applies the
1108            // alias mapping (e.g. `robots.is_allowed` → `is_allowed`), expands array
1109            // segments to `[0]` lookups, and injects `!` after optional intermediates so
1110            // chained access compiles under sound null safety.
1111            Some(f) if !f.is_empty() => field_resolver.accessor(f, "dart", result_var),
1112            _ => result_var.to_string(),
1113        }
1114    };
1115
1116    let format_value = |val: &serde_json::Value| -> String { dart_format_value(val) };
1117
1118    match assertion.assertion_type.as_str() {
1119        "equals" | "field_equals" => {
1120            if let Some(expected) = &assertion.value {
1121                let dart_val = format_value(expected);
1122                // Match the rust codegen's behaviour: trim both sides for string equality
1123                // so trailing-newline differences between h2m's emitted markdown and the
1124                // fixture's expected value don't produce false positives.
1125                if expected.is_string() {
1126                    let _ = writeln!(
1127                        out,
1128                        "    expect({field_accessor}.toString().trim(), equals({dart_val}.toString().trim()));"
1129                    );
1130                } else {
1131                    let _ = writeln!(out, "    expect({field_accessor}, equals({dart_val}));");
1132                }
1133            } else {
1134                let _ = writeln!(
1135                    out,
1136                    "    // skipped: '{}' assertion missing value",
1137                    assertion.assertion_type
1138                );
1139            }
1140        }
1141        "not_equals" => {
1142            if let Some(expected) = &assertion.value {
1143                let dart_val = format_value(expected);
1144                if expected.is_string() {
1145                    let _ = writeln!(
1146                        out,
1147                        "    expect({field_accessor}.toString().trim(), isNot(equals({dart_val}.toString().trim())));"
1148                    );
1149                } else {
1150                    let _ = writeln!(out, "    expect({field_accessor}, isNot(equals({dart_val})));");
1151                }
1152            }
1153        }
1154        "contains" => {
1155            if let Some(expected) = &assertion.value {
1156                let dart_val = format_value(expected);
1157                let _ = writeln!(out, "    expect({field_accessor}, contains({dart_val}));");
1158            } else {
1159                let _ = writeln!(out, "    // skipped: 'contains' assertion missing value");
1160            }
1161        }
1162        "contains_all" => {
1163            if let Some(values) = &assertion.values {
1164                for val in values {
1165                    let dart_val = format_value(val);
1166                    let _ = writeln!(out, "    expect({field_accessor}, contains({dart_val}));");
1167                }
1168            }
1169        }
1170        "contains_any" => {
1171            if let Some(values) = &assertion.values {
1172                let checks: Vec<String> = values
1173                    .iter()
1174                    .map(|v| {
1175                        let dart_val = format_value(v);
1176                        format!("{field_accessor}.contains({dart_val})")
1177                    })
1178                    .collect();
1179                let joined = checks.join(" || ");
1180                let _ = writeln!(out, "    expect({joined}, isTrue);");
1181            }
1182        }
1183        "not_contains" => {
1184            if let Some(expected) = &assertion.value {
1185                let dart_val = format_value(expected);
1186                let _ = writeln!(out, "    expect({field_accessor}, isNot(contains({dart_val})));");
1187            } else if let Some(values) = &assertion.values {
1188                for val in values {
1189                    let dart_val = format_value(val);
1190                    let _ = writeln!(out, "    expect({field_accessor}, isNot(contains({dart_val})));");
1191                }
1192            }
1193        }
1194        "not_empty" => {
1195            // `isNotEmpty` only applies to types with a `.isEmpty` getter (collections,
1196            // strings, maps). For struct-shaped fields (e.g. `document: DocumentStructure`)
1197            // we instead assert the value is non-null — those types have no notion of
1198            // "empty" and the fixture intent is "the field is present".
1199            let is_collection = assertion.field.as_deref().is_some_and(|f| {
1200                let resolved = field_resolver.resolve(f);
1201                field_resolver.is_array(f) || field_resolver.is_array(resolved)
1202            });
1203            if is_collection {
1204                let _ = writeln!(out, "    expect({field_accessor}, isNotEmpty);");
1205            } else {
1206                let _ = writeln!(out, "    expect({field_accessor}, isNotNull);");
1207            }
1208        }
1209        "is_empty" => {
1210            // FRB models `Option<String>` / `Option<Vec<T>>` as nullable in Dart. The `isEmpty`
1211            // matcher throws `NoSuchMethodError` on `null`. Accept `null` as semantically
1212            // empty by combining `isNull` with `isEmpty` via `anyOf`.
1213            let _ = writeln!(out, "    expect({field_accessor}, anyOf(isNull, isEmpty));");
1214        }
1215        "starts_with" => {
1216            if let Some(expected) = &assertion.value {
1217                let dart_val = format_value(expected);
1218                let _ = writeln!(out, "    expect({field_accessor}, startsWith({dart_val}));");
1219            }
1220        }
1221        "ends_with" => {
1222            if let Some(expected) = &assertion.value {
1223                let dart_val = format_value(expected);
1224                let _ = writeln!(out, "    expect({field_accessor}, endsWith({dart_val}));");
1225            }
1226        }
1227        "min_length" => {
1228            if let Some(val) = &assertion.value {
1229                if let Some(n) = val.as_u64() {
1230                    let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
1231                    let _ = writeln!(out, "    expect({length_expr}, greaterThanOrEqualTo({n}));");
1232                }
1233            }
1234        }
1235        "max_length" => {
1236            if let Some(val) = &assertion.value {
1237                if let Some(n) = val.as_u64() {
1238                    let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
1239                    let _ = writeln!(out, "    expect({length_expr}, lessThanOrEqualTo({n}));");
1240                }
1241            }
1242        }
1243        "count_equals" => {
1244            if let Some(val) = &assertion.value {
1245                if let Some(n) = val.as_u64() {
1246                    let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
1247                    let _ = writeln!(out, "    expect({length_expr}, equals({n}));");
1248                }
1249            }
1250        }
1251        "count_min" => {
1252            if let Some(val) = &assertion.value {
1253                if let Some(n) = val.as_u64() {
1254                    let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
1255                    let _ = writeln!(out, "    expect({length_expr}, greaterThanOrEqualTo({n}));");
1256                }
1257            }
1258        }
1259        "matches_regex" => {
1260            if let Some(expected) = &assertion.value {
1261                let dart_val = format_value(expected);
1262                let _ = writeln!(out, "    expect({field_accessor}, matches(RegExp({dart_val})));");
1263            }
1264        }
1265        "is_true" => {
1266            let _ = writeln!(out, "    expect({field_accessor}, isTrue);");
1267        }
1268        "is_false" => {
1269            let _ = writeln!(out, "    expect({field_accessor}, isFalse);");
1270        }
1271        "greater_than" => {
1272            if let Some(val) = &assertion.value {
1273                let dart_val = format_value(val);
1274                let _ = writeln!(out, "    expect({field_accessor}, greaterThan({dart_val}));");
1275            }
1276        }
1277        "less_than" => {
1278            if let Some(val) = &assertion.value {
1279                let dart_val = format_value(val);
1280                let _ = writeln!(out, "    expect({field_accessor}, lessThan({dart_val}));");
1281            }
1282        }
1283        "greater_than_or_equal" => {
1284            if let Some(val) = &assertion.value {
1285                let dart_val = format_value(val);
1286                let _ = writeln!(out, "    expect({field_accessor}, greaterThanOrEqualTo({dart_val}));");
1287            }
1288        }
1289        "less_than_or_equal" => {
1290            if let Some(val) = &assertion.value {
1291                let dart_val = format_value(val);
1292                let _ = writeln!(out, "    expect({field_accessor}, lessThanOrEqualTo({dart_val}));");
1293            }
1294        }
1295        "not_null" => {
1296            let _ = writeln!(out, "    expect({field_accessor}, isNotNull);");
1297        }
1298        "not_error" => {
1299            // The `await` already guarantees no thrown error reaches this point, but
1300            // emit an explicit `expect` on `result` so the test body is non-empty
1301            // (consumes the local, avoiding unused-local-variable hints) and matches
1302            // the python/ruby/node generators which both assert on the result here.
1303            let _ = writeln!(out, "    expect({result_var}, isNotNull);");
1304        }
1305        "error" => {
1306            // Handled at the test method level via throwsA(anything).
1307        }
1308        "method_result" => {
1309            if let Some(method) = &assertion.method {
1310                let dart_method = method.to_lower_camel_case();
1311                let check = assertion.check.as_deref().unwrap_or("not_null");
1312                let method_call = format!("{field_accessor}.{dart_method}()");
1313                match check {
1314                    "equals" => {
1315                        if let Some(expected) = &assertion.value {
1316                            let dart_val = format_value(expected);
1317                            let _ = writeln!(out, "    expect({method_call}, equals({dart_val}));");
1318                        }
1319                    }
1320                    "is_true" => {
1321                        let _ = writeln!(out, "    expect({method_call}, isTrue);");
1322                    }
1323                    "is_false" => {
1324                        let _ = writeln!(out, "    expect({method_call}, isFalse);");
1325                    }
1326                    "greater_than_or_equal" => {
1327                        if let Some(val) = &assertion.value {
1328                            let dart_val = format_value(val);
1329                            let _ = writeln!(out, "    expect({method_call}, greaterThanOrEqualTo({dart_val}));");
1330                        }
1331                    }
1332                    "count_min" => {
1333                        if let Some(val) = &assertion.value {
1334                            if let Some(n) = val.as_u64() {
1335                                let _ = writeln!(out, "    expect({method_call}.length, greaterThanOrEqualTo({n}));");
1336                            }
1337                        }
1338                    }
1339                    _ => {
1340                        let _ = writeln!(out, "    expect({method_call}, isNotNull);");
1341                    }
1342                }
1343            }
1344        }
1345        other => {
1346            let _ = writeln!(out, "    // skipped: unknown assertion type '{other}'");
1347        }
1348    }
1349}
1350
1351/// Render a single fixture assertion for a streaming result.
1352///
1353/// `result_var` is the `List<T>` collected via `.toList()` on the stream.
1354/// Supports:
1355/// - `not_error`: `expect(result, isNotNull)` (a thrown error would already fail
1356///   the test; the explicit expect keeps the test body non-empty).
1357/// - `count_min` with `field = "chunks"`: assert `result_var.length >= value`.
1358/// - `equals` with `field = "stream_content"`: concatenate `delta.content` and compare.
1359///
1360/// Other assertion types are emitted as comments.
1361fn render_streaming_assertion_dart(out: &mut String, assertion: &Assertion, result_var: &str) {
1362    match assertion.assertion_type.as_str() {
1363        "not_error" => {
1364            // `.toList()` would have thrown to fail the test on error; emit an
1365            // explicit `expect` so the test body isn't empty and the collected
1366            // stream variable is consumed.
1367            let _ = writeln!(out, "    expect({result_var}, isNotNull);");
1368        }
1369        "count_min" if assertion.field.as_deref() == Some("chunks") => {
1370            if let Some(serde_json::Value::Number(n)) = &assertion.value {
1371                let _ = writeln!(out, "    expect({result_var}.length, greaterThanOrEqualTo({n}));");
1372            }
1373        }
1374        "equals" if assertion.field.as_deref() == Some("stream_content") => {
1375            if let Some(serde_json::Value::String(expected)) = &assertion.value {
1376                let escaped = escape_dart(expected);
1377                let _ = writeln!(
1378                    out,
1379                    "    final _content = {result_var}.map((c) => c.choices.firstOrNull?.delta.content ?? '').join();"
1380                );
1381                let _ = writeln!(out, "    expect(_content, equals('{escaped}'));");
1382            }
1383        }
1384        other => {
1385            let _ = writeln!(out, "    // skipped streaming assertion: '{other}'");
1386        }
1387    }
1388}
1389
1390/// Converts a snake_case JSON key to Dart camelCase.
1391fn snake_to_camel(s: &str) -> String {
1392    let mut result = String::with_capacity(s.len());
1393    let mut next_upper = false;
1394    for ch in s.chars() {
1395        if ch == '_' {
1396            next_upper = true;
1397        } else if next_upper {
1398            result.extend(ch.to_uppercase());
1399            next_upper = false;
1400        } else {
1401            result.push(ch);
1402        }
1403    }
1404    result
1405}
1406
1407/// Convert a dot-separated fixture field path to a Dart accessor expression.
1408///
1409/// Each segment is converted to camelCase (FRB v2 convention); array-index brackets
1410/// (e.g. `choices[0]`) and map-key brackets (e.g. `tags[name]`) are preserved.
1411/// This replaces the former single-pass `snake_to_camel` call which incorrectly
1412/// treated the entire path string as one identifier.
1413///
1414/// Examples:
1415/// - `"choices"` → `"choices"`
1416/// - `"choices[0].message.content"` → `"choices[0].message.content"`
1417/// - `"metadata.document_title"` → `"metadata.documentTitle"`
1418/// - `"model_id"` → `"modelId"`
1419fn field_to_dart_accessor(path: &str) -> String {
1420    let mut result = String::with_capacity(path.len());
1421    for (i, segment) in path.split('.').enumerate() {
1422        if i > 0 {
1423            result.push('.');
1424        }
1425        // Separate a trailing `[...]` bracket from the field name so we only
1426        // camelCase the identifier part, not the bracket content. The owning
1427        // collection may be `List<T>?` when the underlying Rust field is
1428        // `Option<Vec<T>>`; force-unwrap with `!` so the `[N]` lookup and any
1429        // subsequent member access compile under sound null safety.
1430        if let Some(bracket_pos) = segment.find('[') {
1431            let name = &segment[..bracket_pos];
1432            let bracket = &segment[bracket_pos..];
1433            result.push_str(&name.to_lower_camel_case());
1434            result.push('!');
1435            result.push_str(bracket);
1436        } else {
1437            result.push_str(&segment.to_lower_camel_case());
1438        }
1439    }
1440    result
1441}
1442
1443/// Emits a Dart `ExtractionConfig(...)` constructor with default values, overriding
1444/// fields present in `overrides` (from fixture JSON, snake_case keys).
1445///
1446/// Only simple scalar overrides (bool, int) are supported. Complex nested types
1447/// (ocr, chunking, etc.) are left at their defaults (null).
1448fn emit_extraction_config_dart(overrides: &serde_json::Map<String, serde_json::Value>) -> String {
1449    // Collect scalar overrides; convert keys to camelCase.
1450    let mut field_overrides: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1451    for (key, val) in overrides {
1452        let camel = snake_to_camel(key);
1453        let dart_val = match val {
1454            serde_json::Value::Bool(b) => {
1455                if *b {
1456                    "true".to_string()
1457                } else {
1458                    "false".to_string()
1459                }
1460            }
1461            serde_json::Value::Number(n) => n.to_string(),
1462            serde_json::Value::String(s) => format!("'{s}'"),
1463            _ => continue, // skip complex nested objects
1464        };
1465        field_overrides.insert(camel, dart_val);
1466    }
1467
1468    let use_cache = field_overrides.remove("useCache").unwrap_or_else(|| "true".to_string());
1469    let enable_quality_processing = field_overrides
1470        .remove("enableQualityProcessing")
1471        .unwrap_or_else(|| "true".to_string());
1472    let force_ocr = field_overrides
1473        .remove("forceOcr")
1474        .unwrap_or_else(|| "false".to_string());
1475    let disable_ocr = field_overrides
1476        .remove("disableOcr")
1477        .unwrap_or_else(|| "false".to_string());
1478    let include_document_structure = field_overrides
1479        .remove("includeDocumentStructure")
1480        .unwrap_or_else(|| "false".to_string());
1481    let use_layout_for_markdown = field_overrides
1482        .remove("useLayoutForMarkdown")
1483        .unwrap_or_else(|| "false".to_string());
1484    let max_archive_depth = field_overrides
1485        .remove("maxArchiveDepth")
1486        .unwrap_or_else(|| "3".to_string());
1487
1488    format!(
1489        "ExtractionConfig(useCache: {use_cache}, enableQualityProcessing: {enable_quality_processing}, forceOcr: {force_ocr}, disableOcr: {disable_ocr}, resultFormat: ResultFormat.unified, outputFormat: OutputFormat.plain(), includeDocumentStructure: {include_document_structure}, useLayoutForMarkdown: {use_layout_for_markdown}, maxArchiveDepth: {max_archive_depth})"
1490    )
1491}
1492
1493// ---------------------------------------------------------------------------
1494// HTTP server test rendering — DartTestClientRenderer impl + thin driver wrapper
1495// ---------------------------------------------------------------------------
1496
1497/// Renderer that emits `package:test` `test(...)` blocks using `dart:io HttpClient`
1498/// against the mock server (`Platform.environment['MOCK_SERVER_URL']`).
1499///
1500/// Skipped tests are emitted as self-contained stubs (complete test block with
1501/// `markTestSkipped`) entirely inside `render_test_open`. `render_test_close` uses
1502/// `in_skip` to emit the right closing token: nothing extra for skip stubs (already
1503/// closed) vs. `})));` for regular tests.
1504///
1505/// `is_redirect` must be set to `true` before invoking the shared driver for 3xx
1506/// fixtures so that `render_call` can inject `ioReq.followRedirects = false` after
1507/// the `openUrl` call.
1508struct DartTestClientRenderer {
1509    /// Set to `true` when `render_test_open` is called with a skip reason so that
1510    /// `render_test_close` can match the opening shape.
1511    in_skip: Cell<bool>,
1512    /// Pre-set to `true` by the thin wrapper when the fixture expects a 3xx response.
1513    /// `render_call` injects `ioReq.followRedirects = false` when this is `true`.
1514    is_redirect: Cell<bool>,
1515}
1516
1517impl DartTestClientRenderer {
1518    fn new(is_redirect: bool) -> Self {
1519        Self {
1520            in_skip: Cell::new(false),
1521            is_redirect: Cell::new(is_redirect),
1522        }
1523    }
1524}
1525
1526impl client::TestClientRenderer for DartTestClientRenderer {
1527    fn language_name(&self) -> &'static str {
1528        "dart"
1529    }
1530
1531    /// Emit the test opening.
1532    ///
1533    /// For skipped fixtures: emit the entire self-contained stub (open + body +
1534    /// close + blank line) and set `in_skip = true` so `render_test_close` is a
1535    /// no-op.
1536    ///
1537    /// For active fixtures: emit `test('desc', () => _serialized(() => _withRetry(() async {`
1538    /// leaving the block open for the assertion primitives.
1539    fn render_test_open(&self, out: &mut String, _fn_name: &str, description: &str, skip_reason: Option<&str>) {
1540        let escaped_desc = escape_dart(description);
1541        if let Some(reason) = skip_reason {
1542            let escaped_reason = escape_dart(reason);
1543            let _ = writeln!(out, "  test('{escaped_desc}', () {{");
1544            let _ = writeln!(out, "    markTestSkipped('{escaped_reason}');");
1545            let _ = writeln!(out, "  }});");
1546            let _ = writeln!(out);
1547            self.in_skip.set(true);
1548        } else {
1549            let _ = writeln!(
1550                out,
1551                "  test('{escaped_desc}', () => _serialized(() => _withRetry(() async {{"
1552            );
1553            self.in_skip.set(false);
1554        }
1555    }
1556
1557    /// Emit the test closing token.
1558    ///
1559    /// No-op for skip stubs (the stub was fully closed in `render_test_open`).
1560    /// Emits `})));` followed by a blank line for regular tests.
1561    fn render_test_close(&self, out: &mut String) {
1562        if self.in_skip.get() {
1563            // Stub was already closed in render_test_open.
1564            return;
1565        }
1566        let _ = writeln!(out, "  }})));");
1567        let _ = writeln!(out);
1568    }
1569
1570    /// Emit the full `dart:io HttpClient` request scaffolding.
1571    ///
1572    /// Emits:
1573    /// - URL construction from `MOCK_SERVER_URL`.
1574    /// - `_httpClient.openUrl(method, uri)`.
1575    /// - `followRedirects = false` when `is_redirect` is pre-set on the renderer.
1576    /// - Content-Type header, request headers, cookies, optional body bytes.
1577    /// - `ioReq.close()` → `ioResp`.
1578    /// - Response-body drain into `bodyStr` (skipped for redirect responses).
1579    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
1580        // dart:io restricted headers (handled automatically by the HTTP stack).
1581        const DART_RESTRICTED_HEADERS: &[&str] = &["content-length", "host", "transfer-encoding"];
1582
1583        let method = ctx.method.to_uppercase();
1584        let escaped_method = escape_dart(&method);
1585
1586        // Fixture path is `/fixtures/<id>` — extract the id portion for URL construction.
1587        let fixture_path = escape_dart(ctx.path);
1588
1589        // Determine effective content-type.
1590        let has_explicit_content_type = ctx.headers.keys().any(|k| k.to_lowercase() == "content-type");
1591        let effective_content_type = if has_explicit_content_type {
1592            ctx.headers
1593                .iter()
1594                .find(|(k, _)| k.to_lowercase() == "content-type")
1595                .map(|(_, v)| v.as_str())
1596                .unwrap_or("application/json")
1597        } else if ctx.body.is_some() {
1598            ctx.content_type.unwrap_or("application/json")
1599        } else {
1600            ""
1601        };
1602
1603        let _ = writeln!(
1604            out,
1605            "    final baseUrl = Platform.environment['MOCK_SERVER_URL'] ?? 'http://localhost:8080';"
1606        );
1607        let _ = writeln!(out, "    final uri = Uri.parse('$baseUrl{fixture_path}');");
1608        let _ = writeln!(
1609            out,
1610            "    final ioReq = await _httpClient.openUrl('{escaped_method}', uri);"
1611        );
1612
1613        // Disable automatic redirect following for 3xx fixtures so the test can
1614        // assert on the redirect status code itself.
1615        if self.is_redirect.get() {
1616            let _ = writeln!(out, "    ioReq.followRedirects = false;");
1617        }
1618
1619        // Set content-type header.
1620        if !effective_content_type.is_empty() {
1621            let escaped_ct = escape_dart(effective_content_type);
1622            let _ = writeln!(out, "    ioReq.headers.set('content-type', '{escaped_ct}');");
1623        }
1624
1625        // Set request headers (skip dart:io restricted headers and content-type, already handled).
1626        let mut header_pairs: Vec<(&String, &String)> = ctx.headers.iter().collect();
1627        header_pairs.sort_by_key(|(k, _)| k.as_str());
1628        for (name, value) in &header_pairs {
1629            if DART_RESTRICTED_HEADERS.contains(&name.to_lowercase().as_str()) {
1630                continue;
1631            }
1632            if name.to_lowercase() == "content-type" {
1633                continue; // Already handled above.
1634            }
1635            let escaped_name = escape_dart(&name.to_lowercase());
1636            let escaped_value = escape_dart(value);
1637            let _ = writeln!(out, "    ioReq.headers.set('{escaped_name}', '{escaped_value}');");
1638        }
1639
1640        // Add cookies.
1641        if !ctx.cookies.is_empty() {
1642            let mut cookie_pairs: Vec<(&String, &String)> = ctx.cookies.iter().collect();
1643            cookie_pairs.sort_by_key(|(k, _)| k.as_str());
1644            let cookie_str: Vec<String> = cookie_pairs.iter().map(|(k, v)| format!("{k}={v}")).collect();
1645            let cookie_header = escape_dart(&cookie_str.join("; "));
1646            let _ = writeln!(out, "    ioReq.headers.set('cookie', '{cookie_header}');");
1647        }
1648
1649        // Write body bytes if present (bypass charset-based encoding issues).
1650        if let Some(body) = ctx.body {
1651            let json_str = serde_json::to_string(body).unwrap_or_default();
1652            let escaped = escape_dart(&json_str);
1653            let _ = writeln!(out, "    final bodyBytes = utf8.encode('{escaped}');");
1654            let _ = writeln!(out, "    ioReq.add(bodyBytes);");
1655        }
1656
1657        let _ = writeln!(out, "    final ioResp = await ioReq.close();");
1658        // Drain the response body to bind `bodyStr` for assertion primitives and to
1659        // allow the server to cleanly close the connection (prevents RST packets).
1660        // Redirect responses have no body to drain — skip to avoid a potential hang.
1661        if !self.is_redirect.get() {
1662            let _ = writeln!(out, "    final bodyStr = await ioResp.transform(utf8.decoder).join();");
1663        };
1664    }
1665
1666    fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
1667        let _ = writeln!(
1668            out,
1669            "    expect(ioResp.statusCode, equals({status}), reason: 'status code mismatch');"
1670        );
1671    }
1672
1673    /// Emit a single header assertion, handling special tokens `<<present>>`,
1674    /// `<<absent>>`, and `<<uuid>>`.
1675    fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
1676        let escaped_name = escape_dart(&name.to_lowercase());
1677        match expected {
1678            "<<present>>" => {
1679                let _ = writeln!(
1680                    out,
1681                    "    expect(ioResp.headers.value('{escaped_name}'), isNotNull, reason: 'header {escaped_name} should be present');"
1682                );
1683            }
1684            "<<absent>>" => {
1685                let _ = writeln!(
1686                    out,
1687                    "    expect(ioResp.headers.value('{escaped_name}'), isNull, reason: 'header {escaped_name} should be absent');"
1688                );
1689            }
1690            "<<uuid>>" => {
1691                let _ = writeln!(
1692                    out,
1693                    "    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');"
1694                );
1695            }
1696            exact => {
1697                let escaped_value = escape_dart(exact);
1698                let _ = writeln!(
1699                    out,
1700                    "    expect(ioResp.headers.value('{escaped_name}'), contains('{escaped_value}'), reason: 'header {escaped_name} mismatch');"
1701                );
1702            }
1703        }
1704    }
1705
1706    /// Emit an exact-equality body assertion.
1707    ///
1708    /// String bodies are compared as decoded text; structured JSON bodies are
1709    /// compared via `jsonDecode`.
1710    fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
1711        match expected {
1712            serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
1713                let json_str = serde_json::to_string(expected).unwrap_or_default();
1714                let escaped = escape_dart(&json_str);
1715                let _ = writeln!(out, "    final bodyJson = jsonDecode(bodyStr);");
1716                let _ = writeln!(out, "    final expectedJson = jsonDecode('{escaped}');");
1717                let _ = writeln!(
1718                    out,
1719                    "    expect(bodyJson, equals(expectedJson), reason: 'body mismatch');"
1720                );
1721            }
1722            serde_json::Value::String(s) => {
1723                let escaped = escape_dart(s);
1724                let _ = writeln!(
1725                    out,
1726                    "    expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
1727                );
1728            }
1729            other => {
1730                let escaped = escape_dart(&other.to_string());
1731                let _ = writeln!(
1732                    out,
1733                    "    expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
1734                );
1735            }
1736        }
1737    }
1738
1739    /// Emit partial-body assertions — every key in `expected` must match the
1740    /// corresponding field in the parsed JSON response.
1741    fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
1742        let _ = writeln!(
1743            out,
1744            "    final partialJson = jsonDecode(bodyStr) as Map<String, dynamic>;"
1745        );
1746        if let Some(obj) = expected.as_object() {
1747            for (idx, (key, val)) in obj.iter().enumerate() {
1748                let escaped_key = escape_dart(key);
1749                let json_val = serde_json::to_string(val).unwrap_or_default();
1750                let escaped_val = escape_dart(&json_val);
1751                // Use an index-based variable name so keys with special characters
1752                // don't produce invalid Dart identifiers.
1753                let _ = writeln!(out, "    final _expectedField{idx} = jsonDecode('{escaped_val}');");
1754                let _ = writeln!(
1755                    out,
1756                    "    expect(partialJson['{escaped_key}'], equals(_expectedField{idx}), reason: 'partial body field \\'{escaped_key}\\' mismatch');"
1757                );
1758            }
1759        }
1760    }
1761
1762    /// Emit validation-error assertions for 422 responses.
1763    fn render_assert_validation_errors(
1764        &self,
1765        out: &mut String,
1766        _response_var: &str,
1767        errors: &[ValidationErrorExpectation],
1768    ) {
1769        let _ = writeln!(out, "    final errBody = jsonDecode(bodyStr) as Map<String, dynamic>;");
1770        let _ = writeln!(out, "    final errList = (errBody['errors'] ?? []) as List<dynamic>;");
1771        for ve in errors {
1772            let loc_dart: Vec<String> = ve.loc.iter().map(|s| format!("'{}'", escape_dart(s))).collect();
1773            let loc_str = loc_dart.join(", ");
1774            let escaped_msg = escape_dart(&ve.msg);
1775            let _ = writeln!(
1776                out,
1777                "    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}');"
1778            );
1779        }
1780    }
1781}
1782
1783/// Render a `package:test` `test(...)` block for an HTTP server fixture.
1784///
1785/// Delegates to the shared [`client::http_call::render_http_test`] driver via
1786/// [`DartTestClientRenderer`]. HTTP 101 (WebSocket upgrade) fixtures are emitted
1787/// as skip stubs before reaching the driver because `dart:io HttpClient` cannot
1788/// handle protocol-switch responses.
1789fn render_http_test_case(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
1790    // HTTP 101 (WebSocket upgrade) — dart:io HttpClient cannot handle upgrade responses.
1791    if http.expected_response.status_code == 101 {
1792        let description = escape_dart(&fixture.description);
1793        let _ = writeln!(out, "  test('{description}', () {{");
1794        let _ = writeln!(
1795            out,
1796            "    markTestSkipped('Skipped: Dart HttpClient cannot handle 101 Switching Protocols responses');"
1797        );
1798        let _ = writeln!(out, "  }});");
1799        let _ = writeln!(out);
1800        return;
1801    }
1802
1803    // Pre-set `is_redirect` on the renderer so `render_call` can inject
1804    // `ioReq.followRedirects = false` for 3xx fixtures. The shared driver has no
1805    // concept of expected status code so we thread it through renderer state.
1806    let is_redirect = http.expected_response.status_code / 100 == 3;
1807    client::http_call::render_http_test(out, &DartTestClientRenderer::new(is_redirect), fixture);
1808}
1809
1810/// Infer a MIME type from a file path extension.
1811///
1812/// Returns `None` when the extension is unknown so the caller can supply a fallback.
1813/// Used in dart e2e tests when a fixture omits `mime_type` but uses a `file_path` arg.
1814fn mime_from_extension(path: &str) -> Option<&'static str> {
1815    let ext = path.rsplit('.').next()?;
1816    match ext.to_lowercase().as_str() {
1817        "docx" => Some("application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
1818        "xlsx" => Some("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
1819        "pptx" => Some("application/vnd.openxmlformats-officedocument.presentationml.presentation"),
1820        "pdf" => Some("application/pdf"),
1821        "txt" | "text" => Some("text/plain"),
1822        "html" | "htm" => Some("text/html"),
1823        "json" => Some("application/json"),
1824        "xml" => Some("application/xml"),
1825        "csv" => Some("text/csv"),
1826        "md" | "markdown" => Some("text/markdown"),
1827        "png" => Some("image/png"),
1828        "jpg" | "jpeg" => Some("image/jpeg"),
1829        "gif" => Some("image/gif"),
1830        "zip" => Some("application/zip"),
1831        "odt" => Some("application/vnd.oasis.opendocument.text"),
1832        "ods" => Some("application/vnd.oasis.opendocument.spreadsheet"),
1833        "odp" => Some("application/vnd.oasis.opendocument.presentation"),
1834        "rtf" => Some("application/rtf"),
1835        "epub" => Some("application/epub+zip"),
1836        "msg" => Some("application/vnd.ms-outlook"),
1837        "eml" => Some("message/rfc822"),
1838        _ => None,
1839    }
1840}
1841
1842/// Emit Dart constructors for a batch item array (`BatchBytesItem` or `BatchFileItem`).
1843///
1844/// Returns a Dart list literal like:
1845/// ```dart
1846/// [BatchBytesItem(content: Uint8List.fromList([72, 101, ...]), mimeType: 'text/plain')]
1847/// ```
1848fn emit_dart_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
1849    let items: Vec<String> = arr
1850        .as_array()
1851        .map(|a| a.as_slice())
1852        .unwrap_or_default()
1853        .iter()
1854        .filter_map(|item| {
1855            let obj = item.as_object()?;
1856            match elem_type {
1857                "BatchBytesItem" => {
1858                    let content_bytes = obj
1859                        .get("content")
1860                        .and_then(|v| v.as_array())
1861                        .map(|arr| {
1862                            let nums: Vec<String> =
1863                                arr.iter().filter_map(|v| v.as_u64().map(|n| n.to_string())).collect();
1864                            format!("Uint8List.fromList([{}])", nums.join(", "))
1865                        })
1866                        .unwrap_or_else(|| "Uint8List(0)".to_string());
1867                    let mime_type = obj
1868                        .get("mime_type")
1869                        .and_then(|v| v.as_str())
1870                        .unwrap_or("application/octet-stream");
1871                    Some(format!(
1872                        "BatchBytesItem(content: {content_bytes}, mimeType: '{}')",
1873                        escape_dart(mime_type)
1874                    ))
1875                }
1876                "BatchFileItem" => {
1877                    let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1878                    Some(format!("BatchFileItem(path: '{}')", escape_dart(path)))
1879                }
1880                _ => None,
1881            }
1882        })
1883        .collect();
1884    format!("[{}]", items.join(", "))
1885}
1886
1887/// Escape a string for embedding in a Dart single-quoted string literal.
1888pub(super) fn escape_dart(s: &str) -> String {
1889    s.replace('\\', "\\\\")
1890        .replace('\'', "\\'")
1891        .replace('\n', "\\n")
1892        .replace('\r', "\\r")
1893        .replace('\t', "\\t")
1894        .replace('$', "\\$")
1895}
1896
1897/// Derive the Dart top-level helper function name for constructing a mirror type from JSON.
1898///
1899/// The alef dart bridge-crate generator emits a Rust free function
1900/// `create_<snake_type>_from_json(json: String)` for each non-opaque mirror struct.
1901/// FRB generates the corresponding Dart function as `createTypeNameFromJson` (camelCase).
1902///
1903/// Example: `"ChatCompletionRequest"` → `"createChatCompletionRequestFromJson"`.
1904fn type_name_to_create_from_json_dart(type_name: &str) -> String {
1905    // Convert PascalCase type name to snake_case.
1906    let mut snake = String::with_capacity(type_name.len() + 8);
1907    for (i, ch) in type_name.char_indices() {
1908        if ch.is_uppercase() {
1909            if i > 0 {
1910                snake.push('_');
1911            }
1912            snake.extend(ch.to_lowercase());
1913        } else {
1914            snake.push(ch);
1915        }
1916    }
1917    // snake is now e.g. "chat_completion_request"
1918    // Full Rust function name: "create_chat_completion_request_from_json"
1919    let rust_fn = format!("create_{snake}_from_json");
1920    // Convert to Dart camelCase: "createChatCompletionRequestFromJson"
1921    rust_fn
1922        .split('_')
1923        .enumerate()
1924        .map(|(i, part)| {
1925            if i == 0 {
1926                part.to_string()
1927            } else {
1928                let mut chars = part.chars();
1929                match chars.next() {
1930                    None => String::new(),
1931                    Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
1932                }
1933            }
1934        })
1935        .collect::<Vec<_>>()
1936        .join("")
1937}